DISTINCT
Remove duplicate rows from a result with DISTINCT, and see how NULLs and several columns change the answer.
DISTINCT keeps one of each
SELECT DISTINCT removes duplicate rows from the result. Two rows are duplicates when every selected value is the same.
The opposite is ALL, which keeps every row. ALL is the default, so you only write DISTINCT when you want rows removed.
For this comparison only, two NULL values count as equal. Everywhere else in SQL they do not.
Answer "which values exist?"
Questions like "which teams do we have?" or "which cities do our customers live in?" want each value once. DISTINCT gives you that list without counting or grouping.
DISTINCT works on the whole row
Eight players belong to three teams. This query lists each team once:
SELECT DISTINCT team
FROM players
ORDER BY team;Select two columns and DISTINCT compares the pair: SELECT DISTINCT team, points keeps one row for each different team and points combination. Ben and Hana are both Blue with 17 points, so they make one row. Chen and Eli both have NULL points, but they are on different teams, so their rows stay separate.
PostgreSQL also has DISTINCT ON (column), which keeps the first row of each group. It is an extension, not standard SQL, and "first" is unpredictable unless an ORDER BY decides it.
Watch duplicates collapse
Pick the columns and switch between DISTINCT and all rows. Compare how many rows you get.
| idinteger | nametext | teamtext | pointsinteger |
|---|---|---|---|
| 1 | Asha | Red | 31 |
| 2 | Ben | Blue | 17 |
| 3 | Chen | Red | NULL |
| 4 | Dara | Green | 24 |
| 5 | Eli | Blue | NULL |
| 6 | Fay | Red | 24 |
| 7 | Gus | Green | 40 |
| 8 | Hana | Blue | 17 |
| teamtext |
|---|
| Blue |
| Green |
| Red |
DISTINCT keeps one row for each different value. Eight players, three teams.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- DISTINCT removes rows whose selected values are all the same, and ALL (keep everything) is the default.
- For DISTINCT, NULL values count as equal, so they collapse into one row.
- With several columns, DISTINCT compares the combination of all of them.
- If DISTINCT is hiding unexpected duplicates, look for the cause, often a join.
Done with this concept?
Mark it complete to track your progress. No login needed.