Search code examples
sqliteminimum

Select a single row with minimum column value - sqlite3


I have a table ZZZ with Columns A,B,C,D

I am selecting first X rows of table with column A desc. Sqlite3 query would be

select * from ZZZ order by A desc limit X

How to select the row with minimum value of column B from the result of the above query.

In other words: I want the row with minimum value in column B from a table T. This table T is generated by the query

select * from ZZZ order by A desc limit X

I am using Python sqlite3 interface.


Solution

  • Do just that. Select the row with minimum value in column B from table T:

    SELECT *
    FROM
    (
        SELECT *
        FROM ZZZ
        ORDER BY A DESC
        LIMIT X
    ) T
    ORDER BY B ASC
    LIMIT 1