Sub topic 2
Removing duplicates with SELECT DISTINCT
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query, sort with ORDER BY, and read a table as rows and columns. The examples use a customers table with columns customer_id, name, country, and city. It also uses an orders table.
Why duplicates appear in results
A table's primary key keeps whole rows unique. A query rarely returns whole rows, though. When you select only some columns, different rows can produce identical output.
Suppose customers holds these rows:
| customer_id | name | country | city |
|---|---|---|---|
| 1 | Ana | Spain | Madrid |
| 2 | Ben | Spain | Madrid |
| 3 | Cleo | Spain | Seville |
| 4 | Dan | France | Paris |
| 5 | Eve | NULL | NULL |
| 6 | Finn | NULL | NULL |
This query returns six rows, and Spain appears three times:
SELECT country
FROM customers;Duplicates also come from joins. Joining customers to orders repeats each customer once per order. If you only select customer columns, each customer appears many times.
SQL does not remove duplicates by default. A SELECT returns a multiset, which means a collection where the same row may occur several times. This is a deliberate design choice. Checking for duplicates costs work, so SQL leaves it to you.
Removing duplicates with SELECT DISTINCT
Put the keyword DISTINCT right after SELECT. The database then returns each distinct result row once.
SELECT DISTINCT country
FROM customers;With the sample data, the result has three rows: Spain, France, and NULL. The order of those rows is not guaranteed. Databases often implement DISTINCT with sorting or hashing, so the output may look sorted in one run and scrambled in another. If you need an order, add ORDER BY.
The opposite keyword is ALL, which keeps duplicates. SELECT ALL country behaves like plain SELECT country. You will rarely write it.
DISTINCT applies to the whole row
DISTINCT is not a function, and it does not apply to only the first column. It applies to the entire select list. People often write it with parentheses, which hides this:
-- These two queries are identical in meaning.
SELECT DISTINCT (country), city FROM customers;
SELECT DISTINCT country, city FROM customers;The parentheses only group the expression country. Both queries deduplicate the pair (country, city).
DISTINCT across multiple columns
With several columns, two rows count as duplicates only when every selected column matches.
SELECT DISTINCT country, city
FROM customers
ORDER BY country, city;With the sample data, this returns these rows:
| country | city |
|---|---|
| France | Paris |
| Spain | Madrid |
| Spain | Seville |
| NULL | NULL |
The two Spain, Madrid rows collapse into one. Spain, Seville stays because the city differs. Adding a column to the select list can only keep or increase the number of rows, never reduce it.
A common mistake follows from this. Suppose you want one row per country plus an example city. Writing SELECT DISTINCT country, city does not give one row per country. It gives one row per country and city pair. To get one row per group you need GROUP BY with an aggregate, which later chapters cover.
Another mistake is adding a unique column by habit:
SELECT DISTINCT customer_id, country
FROM customers;Because customer_id is unique, every row is already distinct. The query returns all rows, and the database still pays for the deduplication step.
Counting unique values with COUNT(DISTINCT)
COUNT(DISTINCT column) is an aggregate function. It counts how many different non-NULL values the column holds.
SELECT COUNT(DISTINCT country) AS country_count
FROM customers;With the sample data this returns 2, for Spain and France. The two NULL rows are ignored.
Compare the three counting forms:
| Expression | What it counts | Result on sample data |
|---|---|---|
| `COUNT(*)` | All rows | 6 |
| `COUNT(country)` | Rows where `country` is not NULL | 4 |
| `COUNT(DISTINCT country)` | Different non-NULL country values | 2 |
Note that SELECT COUNT(DISTINCT country) and SELECT DISTINCT COUNT(country) are different queries. The first counts unique values. The second counts all non-NULL values, producing a single row that DISTINCT leaves alone.
Multiple columns inside COUNT
Standard SQL allows only one expression inside COUNT(DISTINCT ...). MySQL accepts a list, as in COUNT(DISTINCT country, city). PostgreSQL and SQL Server reject it. SQLite also rejects it. A portable way to count distinct pairs uses a subquery:
SELECT COUNT(*) AS pair_count
FROM (
SELECT DISTINCT country, city
FROM customers
) AS pairs;This counts the NULL, NULL pair as one row, because the inner DISTINCT keeps it. That differs from the single-column COUNT(DISTINCT), which ignores NULLs. With the sample data it returns 4.
How DISTINCT treats NULL values
In ordinary comparisons, NULL = NULL is not true. It evaluates to unknown. If DISTINCT used that rule, no two NULLs would ever match, and every NULL row would survive.
DISTINCT does the opposite. It treats NULLs as equal to each other for grouping purposes. Standard SQL calls rows "not distinct" from each other when their values are equal or both NULL. So the two NULL rows in the sample data collapse into one.
This applies per column in a multi-column DISTINCT. The rows (Spain, NULL) and (Spain, NULL) are duplicates. The rows (Spain, NULL) and (Spain, Madrid) are not.
Two further edge cases matter in practice:
- Text comparison follows the collation. Collation is the rule set that decides whether
'spain'and'Spain'are equal. In a case-insensitive collation, as in MySQL by default,DISTINCTmerges them. In PostgreSQL's default collations they stay separate. Trailing spaces can also matter, and the rules vary by database. - Some types cannot be deduplicated. Certain types, such as
jsonin PostgreSQL, have no equality operator, soSELECT DISTINCTon them fails. Cast the column to text or usejsonb.
Seeing DISTINCT work
A deduplication step takes the selected rows and keeps one copy of each. The diagram shows the idea with the sample data.
Cost and common pitfalls
DISTINCT is not free. The database must either sort the rows or build a hash table of the values seen so far. On a large result set this takes time and memory. An index on the selected columns can help, because the database can then read the values in order and skip repeats.
Keep these habits:
- Do not use
DISTINCTto hide a bad join. If a join produces unexpected duplicates, the join condition is usually wrong or missing. AddingDISTINCTmakes the symptom vanish while the query still does too much work. Fix the join first. - Use
EXISTSwhen you only need a yes or no. To list customers that have orders,WHERE EXISTS (SELECT 1 FROM orders ...)avoids the repeated rows that a join creates. - Remember that
DISTINCTsees only the selected columns. Two customers named Ana in different cities are different rows ifcityis selected, and the same row if it is not. - Do not rely on the output order. Add
ORDER BYwhen order matters.
Putting it together
Here is a query that combines the ideas. It lists each country that has at least one customer in a city that starts with S, sorted alphabetically.
SELECT DISTINCT country
FROM customers
WHERE city LIKE 'S%'
ORDER BY country;The WHERE clause filters rows first. DISTINCT then removes repeated countries. ORDER BY sorts what remains. A later chapter explains this order of evaluation in full.
Exercise
Using the sample customers table, what does each query return: (a) SELECT DISTINCT country, city FROM customers, (b) SELECT COUNT(DISTINCT country) FROM customers, and (c) SELECT COUNT(DISTINCT country, city) FROM customers in PostgreSQL?
Show answer
(a) Four rows: (France, Paris), (Spain, Madrid), (Spain, Seville), and (NULL, NULL), in no guaranteed order. Rows with the same pair collapse, and NULLs count as equal. (b) The value 2, because only Spain and France are non-NULL country values. (c) An error, because PostgreSQL allows only one expression in COUNT(DISTINCT ...). Use a subquery: SELECT COUNT(*) FROM (SELECT DISTINCT country, city FROM customers) AS pairs, which returns 4.
Exercise
A query joins customers to orders and selects customers.name, and each customer appears once per order. A colleague adds DISTINCT. Name two problems with relying on that fix, and one alternative.
Show answer
First, if two different customers share a name, DISTINCT merges them into one row and you lose data. Second, the database still builds the full joined result and then deduplicates it, which wastes work. An alternative is to select customerid along with name and use WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customerid = customers.customer_id), so each customer appears once without needing DISTINCT.