Dedup: Keep One Row per Group in SQL
GROUP BY, DISTINCT ON, or ROW_NUMBER — DISTINCT alone cannot choose
DISTINCT collapses whole rows but cannot pick which duplicate survives. Choices: GROUP BY with MIN/MAX per group; PostgreSQL DISTINCT ON (first row per group under ORDER BY); portable ROW_NUMBER() partitioned by key ordered by recency with outer rn = 1 (keeps latest per user deterministically with id tiebreak).
DISTINCT cannot choose
Collapses whole rows; survivor is undefined for per-group picks.
GROUP BY picks via agg
MIN/MAX per key — earliest/latest scalar per group.
DISTINCT ON shortcuts (PG)
First row per group under ORDER BY — concise, non-portable.
ROW_NUMBER keeps latest
PARTITION BY key ORDER BY created_at DESC, id DESC; filter rn=1 — portable + deterministic.
1SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) t WHERE rn = 1;
| name | department | salary |
|---|---|---|
| Cynthia | Engineering | 91000 |
| Elena | Sales | 58000 |
| David | Marketing | 47000 |
Partition slices per department, ORDER ranks inside, outer filter keeps each head. DISTINCT could list departments but never attach the top earner’s name.
Top earner per department
Portable keep-one with names attached.
1SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC, id DESC) AS rn FROM employees) t WHERE rn = 1;
| name | department | salary |
|---|---|---|
| Cynthia | Engineering | 91000 |
| Elena | Sales | 58000 |
| David | Marketing | 47000 |
Earliest id per department
GROUP BY fallback without windows.
1SELECT department, MIN(id) AS first_id FROM employees GROUP BY department;
| department | first_id |
|---|---|
| Engineering | 1 |
| Marketing | 4 |
| Sales | 2 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.