Search code examples
mysqlpython-3.xselectlimit

SQL query in python - select rows containing argument from first n rows


I have a test table with 2000 rows and I am trying to select only from the first 1000 rows those rows where xxx = 0.

I tried with:

mydb.cursor().execute("SELECT column_N FROM test_table LIMIT 1000 WHERE xxx = 0")

but this returns an error.

Note: I wish to get the rows containing the argument from within the first 1000 rows and not the first 1000 rows containing the argument.


Solution

  • WHERE clause needs to be placed before LIMIT:

    SELECT column_N 
    FROM test_table 
    WHERE xxx = 0
    -- ORDER BY col_name  -- to have stable resultset, ORDER BY is needed
    LIMIT 1000 
    

    EDIT:

    SELECT s.column_N
    FROM (
        SELECT *
        FROM test_table 
        ORDER BY col_name  -- to have stable first 1000 rows, ORDER BY is needed
        LIMIT 1000) s
    WHERE s.xxx = 0;
    

    Tables are unordered sets, so LIMIT 1000 may vary betweens runs, that is why ORDER BY was added.