ORDER BY and LIMIT

ORDER BY arranges. LIMIT cuts.

Ascending is the default; DESC reverses. Several columns break ties in turn: ORDER BY year DESC, title sorts by year newest first, and orders books from the same year alphabetically.

Try it

Remove the ORDER BY and keep the LIMIT. You still get three rows, but which three is now up to the database.

loading editor…
real SQLite, in your browser

The three most recent. Change DESC to ASC for the three oldest.

✦ LIMIT without ORDER BY is not a top ten

It is an arbitrary ten. The database returns whichever rows it reached first, and that can differ between runs and after an index is added. If the word 'top' appears in the question, ORDER BY is part of the answer.

Paging with OFFSET has the same trap, worse. LIMIT 10 OFFSET 20 needs a sort that is stable and unique, or rows shuffle between pages: someone reading page three sees a row they already saw on page two, and never sees another at all.

Adding the primary key as a final tiebreaker fixes it: ORDER BY year DESC, id.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: DISTINCT →
← Back