ORDER BY and LIMIT
Sorting and paging - and why LIMIT without ORDER BY is a bug waiting to happen.
Open this lesson in the learning hubKey points
ORDER BY col DESCsorts descending; the default is ascending.LIMIT nreturns at most n rows - the standard way to page results.- Without ORDER BY, row order is undefined, so LIMIT can return different rows each run.
- Sorting happens after WHERE and grouping, on the rows that survived.
- A sort on an unindexed column means the database materialises and sorts everything.
LIMIT without ORDER BY gives you arbitrary rows - always pair them.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the MySQL Course course, and every lesson in it is listed on the MySQL Course contents page.