DISTINCT and DISTINCT ON
- Version
- 19
- Review
- Draft
Summary#
DISTINCT returns one copy of each output row. DISTINCT ON returns the first row for each group of equal key values, with ORDER BY deciding which row comes first.
Syntax#
SELECT DISTINCT column_list FROM table_name;
SELECT DISTINCT ON (group_key) column_list
FROM table_name
ORDER BY group_key, priority_column DESC, unique_column DESC;
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE parcel_scans (
scan_id integer PRIMARY KEY,
parcel_id integer NOT NULL,
scan_day date NOT NULL,
location text NOT NULL
);
INSERT INTO parcel_scans VALUES
(1, 41, '2026-06-05', 'intake'),
(2, 41, '2026-06-06', 'sorting'),
(3, 41, '2026-06-06', 'dispatch'),
(4, 42, '2026-06-05', 'intake');
SELECT DISTINCT parcel_id
FROM parcel_scans
ORDER BY parcel_id;
SELECT DISTINCT ON (parcel_id) parcel_id, scan_id, location
FROM parcel_scans
ORDER BY parcel_id, scan_day DESC, scan_id DESC;
ROLLBACK;
Expected output#
parcel_id
41
42
(2 rows)
parcel_id|scan_id|location
41|3|dispatch
42|4|intake
(2 rows)
Common mistakes#
Start ORDER BY with the DISTINCT ON keys. Add a unique tie-breaker after the priority columns so ties pick a repeatable winner. To sort the chosen rows differently, wrap the query and sort in the outer query.
Version applicability#
Both forms work in PostgreSQL 19. DISTINCT ON is a PostgreSQL extension.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0