Search code examples
databasesqliteselectrandomsql-order-by

Get random rows from sqlite database, then sort by column


With each new query I want to obtain a random set of 10 rows from the table tasks. The rows should then be sorted by column difficulty.

I tried this but order by difficulty is ignored:

SELECT id, difficulty
FROM tasks
ORDER BY random(), difficulty
LIMIT 10

Solution

  • First get the 10 random rows in a subquery and then sort them by difficulty:

    SELECT *
    FROM (
      SELECT id, difficulty
      FROM tasks
      ORDER BY random()
      LIMIT 10
    )
    ORDER BY difficulty;