Practical guide

SQL ORDER BY: Sort Query Results

SQL does not guarantee row order unless the query includes ORDER BY. Sorting the output is separate from changing how data is stored.

What to do

  1. Sort names alphabetically with SELECT name FROM customers ORDER BY name ASC;. ASC is the default in many systems.
  2. Sort newest records first with SELECT id, created_at FROM orders ORDER BY created_at DESC;.
  3. Add a tie-breaker for stable ordering, for example ORDER BY city ASC, name ASC.
  4. Combine ORDER BY with a row limit when previewing a large dataset; the limit syntax differs by database.

Checks and limitations

  • Sorting by a non-unique column can leave tied rows in an unspecified order unless a second sort key is added.
  • NULL placement and collation rules can differ across database engines.