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
- Sort names alphabetically with
SELECT name FROM customers ORDER BY name ASC;. ASC is the default in many systems. - Sort newest records first with
SELECT id, created_at FROM orders ORDER BY created_at DESC;. - Add a tie-breaker for stable ordering, for example
ORDER BY city ASC, name ASC. - 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.