Stop 02 · Basic SELECT QueriesTopics · 7/8

ORDER BY (ASC, DESC, Multiple Columns)

Part of the SQL Roadmap

In short

Rows in a table have no built-in order. If you want the biggest orders first or names in alphabetical order, you must ask for it with ORDER BY every single time.

ORDER BY sorts the result by one or more columns, ascending by default or descending with DESC. Without ORDER BY the database is free to return rows in any order, even if it looks sorted.

The jaadu pins report cards onto a school notice board in a neat descending line, tallest stack of stars at the top.

Think of it like this

The board exam merit list

The school notice board lists students by marks, highest first. Two students both scored 487? Then they're listed alphabetically by name. That's ORDER BY marks DESC, name ASC: sort by the first rule, and use the second only to break ties.

Watch it happen

ORDER BY marks DESC, name ASC

Ravi 472
0
Asha 487
1
Kabir 455
2
Zoya 487
3
Dev 472
4

1/4Unsorted rows straight from the table.

The big ideas

What you need to know

ASC is the default

Smallest to largest, A to Z, oldest to newest. You don't need to write ASC.

DESC per column

Each column gets its own direction: ORDER BY marks DESC, name ASC.

No ORDER BY, no promise

Results may look sorted by chance. Without ORDER BY the database is free to change the order.

Where NULLs go

PostgreSQL puts NULLs last in ASC and first in DESC. MySQL does the opposite. Use NULLS LAST in PostgreSQL to control it.

See it in code

Walk through the code

sql
1SELECT student_name, city, marks2FROM results3ORDER BY marks DESC, student_name ASC;4 5-- Latest orders first, missing dates at the end6SELECT order_id, order_date, amount7FROM orders8ORDER BY order_date DESC NULLS LAST;

1/2Highest marks first, ties broken by name A to Z.

NULLS LAST works in PostgreSQL and Oracle. MySQL doesn't support it; use ORDER BY order_date IS NULL, order_date DESC instead.

Save yourself the pain

Common mistakes

Oops

Writing ORDER BY marks, name DESC and expecting both columns descending.

Do this instead

DESC applies only to the column right before it. Write ORDER BY marks DESC, name DESC.

Oops

Relying on rows coming back in insert order.

Do this instead

Always add ORDER BY when order matters, including for top-N and pagination.

Your mission

Make a merit list

~20 min

Quick check

What does ORDER BY city, amount DESC do?

Go deeper

  1. 1Sort products by category and then by price descending within each category.
  2. 2Check where NULLs appear when sorting (first in MySQL ascending, last in PostgreSQL ascending) and try NULLS LAST in PostgreSQL.
  3. 3Never rely on the default row order in a report; always add ORDER BY.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge