Learning navigation

Code with Animation

DISTINCT

Remove duplicate rows from a result with DISTINCT, and see how NULLs and several columns change the answer.

SQL4 min readConcept 10 of 44

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.

SELECT DISTINCT team
FROM players
ORDER BY team;
players (8 rows)
idintegernametextteamtextpointsinteger
1AshaRed31
2BenBlue17
3ChenRedNULL
4DaraGreen24
5EliBlueNULL
6FayRed24
7GusGreen40
8HanaBlue17
Result (3 rows)
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.

  1. 1`SELECT DISTINCT team FROM players` runs on 8 players in 3 teams. How many rows come back?
  2. 2Two players have NULL points. How many NULL rows does `SELECT DISTINCT points FROM players` return?
  3. 3`SELECT DISTINCT team, points FROM players` runs on 8 players. Ben and Hana are both Blue with 17 points. How many rows come back?

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.