skip to content

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.

query.sqlstep 1: FROM
  1. 1SELECT DISTINCT dept, credits
  2. 2FROM courses
  3. 3ORDER BY dept, credits;
the table after FROM
codetextdepttextcreditsint2
CS101CS4
CS201CS4
CS301CS4
CS350CS4
CS401CS4
CS499GEN6
HIST101HIST3
MATH101MATH4
MATH201MATH3
MATH301MATH3
PHYS101PHYS4
PHYS201PHYS4
(12 rows)

FROM hands over all 12 courses.

the query that produced this table
SELECT code, dept, credits FROM courses ORDER BY code
clause 1/4
real output, postgres 18.6 (PGlite 0.5.12) · distinct-rows
step through it. SELECT keeps two columns, and suddenly rows repeat. DISTINCT keeps one of each pair and strikes the copies. the table shows code at FROM, so you can see which courses become which pair.

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:

sqldb=school
EXPLAIN (COSTS OFF) SELECT DISTINCT dept FROM courses;
EXPLAIN (COSTS OFF) SELECT dept FROM courses GROUP BY dept;
output, from postgres 18.6
#1 · EXPLAIN
HashAggregate Group Key: dept -> Seq Scan on courses
#2 · EXPLAIN
HashAggregate Group Key: dept -> Seq Scan on courses

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:

SELECT DISTINCT =
query.sql
  1. 1SELECT DISTINCT name
  2. 2FROM customers
  3. 3WHERE id <= 12
  4. 4ORDER BY name;
the result for name
nametext
Ana Lima
Grace Okafor
José Silva
Maya Chen
Ming Li
Null
Ravi Kumar
Sam Lee
Sean O'Neil
Zoe Martin
Zoë Martin
(11 rows)

by name: the two Sam Lees are one row, though they're two people. Zoë and Zoe Martin stay apart: ë isn't e.

real output, postgres 18.6 (PGlite 0.5.12) · distinct-rows-shop
switch what SELECT asks for. two Sam Lees merge by name and split again by name and city. two NULL emails count as one. and DISTINCT compares what SELECT computed, so 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 what email keeps apart.
  • NULLs are duplicates. for DISTINCT, two NULLs are the same, even though NULL = NULL isn't true. that's NULL's split personality again.
predict the output
sql
SELECT DISTINCT email
FROM customers
WHERE id IN (2, 11, 42);   -- Grace, Ana, Ada
sqldb=shop
SELECT 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);
output, from postgres 18.6
#1 · SELECT 2
emailtext
ada@example.com
null
(2 rows)
#2 · SELECT 1
countint8
1
(1 row)

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:

query.sqlstep 1: FROM
  1. 1SELECT DISTINCT ON (dept) dept, code, credits, title
  2. 2FROM courses
  3. 3ORDER BY dept, credits DESC, code;
the table after FROM
depttextcodetextcreditsint2titletext
CSCS1014Intro to Programming
CSCS2014Data Structures
CSCS3014Databases
CSCS3504Operating Systems
CSCS4014Database Internals
GENCS4996Senior Thesis
HISTHIST1013History of Computing
MATHMATH1014Calculus I
MATHMATH2013Discrete Math
MATHMATH3013Linear Algebra
PHYSPHYS1014Mechanics
PHYSPHYS2014Electromagnetism
(12 rows)

FROM hands over all 12 courses.

the query that produced this table
SELECT dept, code, credits, title FROM courses ORDER BY code
clause 1/3
real output, postgres 18.6 (PGlite 0.5.12) · distinct-rows
step through it. ORDER BY lines the courses up so the one with the most credits comes first in its department (code breaks ties). DISTINCT ON keeps that first row of each department, and strikes the rest.

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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 3
customer_idint4idint4statustextordered_attimestamptz
39607delivered2026-06-12 22:20:00+00
98744delivered2026-05-12 18:45:00+00
429946placed2026-06-25 04:02:00+00
(3 rows)

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:

sqldb=school
SELECT DISTINCT ON (dept) dept, code
FROM courses
ORDER BY credits DESC;
output, from postgres 18.6
ERROR 42P10: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
1 │ SELECT DISTINCT ON (dept) dept, code
at line 1, column 21

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.