Part 02 / Topic 6 of 9
DISTINCT and DISTINCT ON
DISTINCT removes duplicate rows from the result. Which cities do our customers live in?
SELECT DISTINCT city FROM customers ORDER BY city;
city
---------
Chennai
Delhi
London
Pune
(5 rows)
Two things to notice: Pune appears once even though two customers live there, and NULL appears as its own "value" in the list.
Postgres also has DISTINCT ON — keep one whole row per value of something. One product per category — the cheapest one:
SELECT DISTINCT ON (category_id)
category_id, name, price
FROM products
ORDER BY category_id, price;
category_id | name | price
-------------+-------------------+--------
1 | USB-C Cable | 15.00
2 | SQL for Beginners | 35.00
3 | Desk Lamp | 45.00
4 | Laptop Air 13 | 950.00
5 | Phone Lite | 399.00
6 | Chef Knife | 80.00
(6 rows)
The rule: ORDER BY must start with the DISTINCT ON columns; the next sort key decides which row survives (here: lowest price). DISTINCT ON is PostgreSQL-specific and beloved — the portable way to do this needs window functions, which are a Stage 2 lesson.
🧪 Quick quiz — answer from memory, then check.
SELECT DISTINCT city FROM customers— how many times does Pune appear?- What picks which row survives in a
DISTINCT ONquery?
Show the answers
- Once — DISTINCT collapses duplicates in the result.
- The ORDER BY: after the DISTINCT ON columns, the remaining sort keys rank the candidates and the first row per group wins.
Done here? The practice set for Part 2 — 8 exercises with solutions — is on the part page.