Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 02 / Topic 7 of 9

ORDER BY

Without ORDER BY, row order is not guaranteed — Postgres returns whatever is fastest today, and it can change tomorrow. If order matters, say so:

SELECT name, price FROM products ORDER BY price;
        name        |  price  
--------------------+---------
 USB-C Cable        |   15.00
 SQL for Beginners  |   35.00
 Desk Lamp          |   45.00
 Postgres Deep Dive |   55.00
 Chef Knife         |   80.00
 Coffee Maker       |  120.00
 Phone Lite         |  399.00
 Phone X            |  799.00
 Laptop Air 13      |  950.00
 Laptop Pro 14      | 1200.00
(10 rows)

DESC flips it; several sort keys break ties — cheapest first within each category:

SELECT category_id, name, price
FROM products
ORDER BY category_id, price DESC;
 category_id |        name        |  price  
-------------+--------------------+---------
           1 | USB-C Cable        |   15.00
           2 | Postgres Deep Dive |   55.00
           2 | SQL for Beginners  |   35.00
           3 | Desk Lamp          |   45.00
           4 | Laptop Pro 14      | 1200.00
           4 | Laptop Air 13      |  950.00
           5 | Phone X            |  799.00
           5 | Phone Lite         |  399.00
           6 | Coffee Maker       |  120.00
           6 | Chef Knife         |   80.00
(10 rows)

Where do NULLs sort? Postgres treats NULL as larger than every value: last in ascending order, first in descending. Override explicitly:

SELECT first_name, city
FROM customers
ORDER BY city NULLS FIRST;
 first_name |  city   
------------+---------
 Sara       | 
 Meera      | Chennai
 Ravi       | Delhi
 John       | London
 Asha       | Pune
 Vikram     | Pune
(6 rows)

You can also sort by a calculated expression, even one not in the SELECT list — ORDER BY price * stock DESC works fine.

🧪 Quick quiz — answer from memory, then check.

  1. With no ORDER BY, what order do rows come back in?
  2. In ORDER BY price ASC, where do NULL prices appear?
Show the answers
  1. No guaranteed order at all — whatever the executor produced. Never rely on it.
  2. Last — PostgreSQL sorts NULL as larger than any value. NULLS FIRST overrides.

Done here? The practice set for Part 2 — 8 exercises with solutions — is on the part page.

Search the guide