DISTINCT and DISTINCT ON
throwing away duplicates, and postgres's keep-one-row-per-group trick.
- address
- everything.basics.distinct_rows
- part
- part 2, one table
- chapter
- chapter 6 of 12
- reading time
- 7 min
DISTINCT throws away duplicate rows of the result. it compares whole output rows, after SELECT has computed them, and it treats two NULLs as duplicates of each other.
DISTINCT ON (key) is postgres's own: keep the first row of each key, where "first" is whatever your ORDER BY says.
the picture
you know how adding DISTINCT sometimes changes nothing, and sometimes eats rows you wanted to keep? both come from the same rule: DISTINCT doesn't look at a column, it looks at the whole row you asked for. two rows are duplicates only if every column you selected matches.
think of a cloakroom that keeps one ticket per outfit: same coat, same hat, same scarf, one ticket. change the scarf and it's a different outfit. DISTINCT works on the outfit SELECT handed it, not on the person wearing it.
- 1SELECT DISTINCT dept, credits
- 2FROM courses
- 3ORDER BY dept, credits;
| codetext | depttext | creditsint2 |
|---|---|---|
| CS101 | CS | 4 |
| CS201 | CS | 4 |
| CS301 | CS | 4 |
| CS350 | CS | 4 |
| CS401 | CS | 4 |
| CS499 | GEN | 6 |
| HIST101 | HIST | 3 |
| MATH101 | MATH | 4 |
| MATH201 | MATH | 3 |
| MATH301 | MATH | 3 |
| PHYS101 | PHYS | 4 |
| PHYS201 | PHYS | 4 |
FROM hands over all 12 courses.
the query that produced this table
six pairs from twelve courses: exactly the buckets GROUP BY dept, credits would make. that's not a coincidence. DISTINCT is a GROUP BY on every selected column with no aggregates, and postgres often runs them the same way:
EXPLAIN (COSTS OFF) SELECT DISTINCT dept FROM courses;
EXPLAIN (COSTS OFF) SELECT dept FROM courses GROUP BY dept;the same HashAggregate both times. and like GROUP BY, a hash table has no order, so if you want the result sorted, ORDER BY still has to say so.
what counts as a duplicate
the shop's first twelve customers are a good test, because they're full of near-misses on purpose:
- 1SELECT DISTINCT name
- 2FROM customers
- 3WHERE id <= 12
- 4ORDER BY name;
| nametext |
|---|
| Ana Lima |
| Grace Okafor |
| José Silva |
| Maya Chen |
| Ming Li |
| Null |
| Ravi Kumar |
| Sam Lee |
| Sean O'Neil |
| Zoe Martin |
| Zoë Martin |
by name: the two Sam Lees are one row, though they're two people. Zoë and Zoe Martin stay apart: ë isn't e.
lower(email) merges the two Zoe Martin addresses.three rules fall out of it:
- it's the whole row. add a column and two rows that used to match may not anymore. that's why "just add DISTINCT" to a query that returns too many rows usually doesn't help: the duplicates differ in some column you're selecting.
- it's after SELECT. expressions are computed first, then compared.
lower(email)merges whatemailkeeps apart. - NULLs are duplicates. for DISTINCT, two NULLs are the same, even though
NULL = NULLisn't true. that's NULL's split personality again.
SELECT DISTINCT email
FROM customers
WHERE id IN (2, 11, 42); -- Grace, Ana, AdaSELECT DISTINCT email FROM customers WHERE id IN (2, 11, 42) ORDER BY email;
SELECT count(DISTINCT email) FROM customers WHERE id IN (2, 11, 42);| emailtext |
|---|
| ada@example.com |
| null |
| countint8 |
|---|
| 1 |
two rows, but a count of one. SELECT DISTINCT keeps the NULL as a row, and count(DISTINCT) doesn't count it.
DISTINCT ON
plain DISTINCT keeps one row per whole row. very often you want one row per something: one per department, one per customer, and you want to pick which one. postgres has a clause for exactly that. DISTINCT ON (dept) keeps the first row for each dept and throws the rest away, and the ORDER BY decides what "first" means:
- 1SELECT DISTINCT ON (dept) dept, code, credits, title
- 2FROM courses
- 3ORDER BY dept, credits DESC, code;
| depttext | codetext | creditsint2 | titletext |
|---|---|---|---|
| CS | CS101 | 4 | Intro to Programming |
| CS | CS201 | 4 | Data Structures |
| CS | CS301 | 4 | Databases |
| CS | CS350 | 4 | Operating Systems |
| CS | CS401 | 4 | Database Internals |
| GEN | CS499 | 6 | Senior Thesis |
| HIST | HIST101 | 3 | History of Computing |
| MATH | MATH101 | 4 | Calculus I |
| MATH | MATH201 | 3 | Discrete Math |
| MATH | MATH301 | 3 | Linear Algebra |
| PHYS | PHYS101 | 4 | Mechanics |
| PHYS | PHYS201 | 4 | Electromagnetism |
FROM hands over all 12 courses.
the query that produced this table
the classic use is "the latest one of each": each customer's most recent order, each sensor's last reading. here are the newest orders of Toronto's Sam, Seoul's Sam and Ada:
SELECT DISTINCT ON (customer_id) customer_id, id, status, ordered_at
FROM orders
WHERE customer_id IN (3, 9, 42)
ORDER BY customer_id, ordered_at DESC;| customer_idint4 | idint4 | statustext | ordered_attimestamptz |
|---|---|---|---|
| 3 | 9607 | delivered | 2026-06-12 22:20:00+00 |
| 9 | 8744 | delivered | 2026-05-12 18:45:00+00 |
| 42 | 9946 | placed | 2026-06-25 04:02:00+00 |
one row each, and every column of it comes from the same order. that's the part a GROUP BY can't do on its own: max(ordered_at) gives you the date, but not the status that went with it.
two rules keep it honest. the DISTINCT ON keys have to come first in the ORDER BY, because that's how postgres finds where one group ends and the next begins:
SELECT DISTINCT ON (dept) dept, code
FROM courses
ORDER BY credits DESC;and without an ORDER BY after the keys, "the first row" of a group is whichever one the plan happens to meet first, which is the coin toss again. DISTINCT ON is postgres only postgres only. elsewhere you'd write it with row_number(), and top n per group compares the two.
one level deeperDISTINCT as a bandage
when a join returns every customer three times, adding DISTINCT makes the copies go away, and that feels like a fix. usually it's hiding one: the join matched more rows than you thought (join fan-out), and any sum or count you add later will still be counted three times, because aggregates run before DISTINCT does. and DISTINCT isn't free: on a big result it hashes or sorts everything to find the copies. find out why the rows repeat, then fix the join, or use EXISTS, which never duplicates in the first place.
keylines
- DISTINCT compares whole output rows, after SELECT computed them.
- add a column and duplicates can stop being duplicates.
- for DISTINCT, NULLs are duplicates. count(DISTINCT) skips them instead.
- DISTINCT ON (key) keeps the first row per key, first by the ORDER BY, which must start with the key.
- DISTINCT that fixes a join usually hides fan-out. fix the join.