ORDER BY and LIMIT

MySQL Course · lesson 3 of 21 · 3 min read

Sorting and paging - and why LIMIT without ORDER BY is a bug waiting to happen.

Open this lesson in the learning hub

Key points

  • ORDER BY col DESC sorts descending; the default is ascending.
  • LIMIT n returns 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.