Skip to content

Databases

Sorting (ORDER BY)

O(n log n) time for a general sort. A database can often use an index to make ORDER BY cheaper on that column.

The idea, in plain English

ORDER BY is like handing a librarian a stack of books and asking for them back sorted by year. The table's rows do not change. You are only choosing the order you read the results in.

How it works

  1. 1Pick the column or columns to sort by, such as age.
  2. 2Decide the direction. ASC means ascending: smallest first. DESC means descending: biggest first.
  3. 3The database reorders the result rows by comparing that column. It does not change the stored table.

When you'd use it

Use ORDER BY whenever the order of results matters. For example: newest posts first, cheapest products first, or names in alphabetical order.

Common beginner mistakes

  • Do not assume rows come back in a 'natural' order without ORDER BY. SQL makes no such promise unless you ask for one.
  • If you forget DESC, you get smallest-first when you wanted biggest-first.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
SQL: SELECT * FROM users ORDER BY age ASC
4 Dan 22 Multan
1 Ana 28 Lahore
2 Bilal 35 Karachi
3 Cara 41 Lahore
SQL: SELECT * FROM users ORDER BY age DESC
3 Cara 41 Lahore
2 Bilal 35 Karachi
1 Ana 28 Lahore
4 Dan 22 Multan

Not sure this is the right topic? See the learning paths → or where this leads →