Sub topic 3
DISTINCT across multiple columns
This chapter assumes you can write a basic SELECT ... FROM query, filter with WHERE, sort with ORDER BY, and that you know what tables, rows, and columns are. It also assumes you have seen single-column SELECT DISTINCT. Here you will learn how DISTINCT behaves when you list several columns, and which mistakes to avoid.
DISTINCT applies to the whole row
A common misreading of SELECT DISTINCT country, city is that DISTINCT applies only to country. It does not. DISTINCT is not a function and does not attach to the first column. It is a modifier on the whole SELECT list. The database compares complete output rows and keeps one copy of each unique combination.
SELECT DISTINCT country, city
FROM customers
ORDER BY country, city;Here DISTINCT applies to the whole combination of country and city, so each unique pair appears once. If five customers live in Lyon, France, the pair (France, Lyon) appears once. (France, Paris) is a different pair and also appears. Two rows are duplicates only when every selected column matches.
Suppose customers holds these rows:
| customer_id | country | city |
|---|---|---|
| 1 | France | Paris |
| 2 | France | Paris |
| 3 | France | Lyon |
| 4 | Germany | Berlin |
| 5 | Germany | Berlin |
| 6 | Spain | Madrid |
The query above returns:
| country | city |
|---|---|
| France | Lyon |
| France | Paris |
| Germany | Berlin |
| Spain | Madrid |
Six input rows collapse to four unique pairs. Rows 1 and 2 match on both columns, and so do rows 4 and 5.
Adding columns changes the result
Every column you add to the select list can only keep the number of distinct rows the same or increase it. It can never reduce it. Compare these queries:
SELECT DISTINCT country
FROM customers;SELECT DISTINCT country, city
FROM customers;With the sample data, the first returns 3 rows and the second returns 4. If you add a column that is unique per row, such as customer_id, DISTINCT stops removing anything:
SELECT DISTINCT customer_id, country, city
FROM customers;This returns all six rows, because no two rows share a customer_id. This is a frequent source of confusion. A developer sees duplicates, adds DISTINCT, and still sees duplicates. The cause is usually an extra column in the select list, often an ID or timestamp, that makes every row unique.
Column order does not change the set of rows
SELECT DISTINCT country, city and SELECT DISTINCT city, country return the same unique pairs. Only the column order in the output differs. Deduplication depends on which columns are included, not on their order. Row order is a separate matter, covered next.
Row order is not guaranteed
Many databases implement DISTINCT by sorting or by hashing. With a sort-based plan the output often looks sorted. With a hash-based plan it can come out in any order. Neither is a promise. If the order matters, add ORDER BY, as the earlier example does:
SELECT DISTINCT country, city
FROM customers
ORDER BY country, city;Expressions count as columns
DISTINCT works on the values of the select list, including computed expressions. This is useful for collapsing detail into a coarser grouping:
SELECT DISTINCT country, UPPER(city) AS city_upper
FROM customers;Here rows are compared on country and the uppercased city. Paris and PARIS count as the same value after UPPER. Without the function, they would count as different values in a database whose comparison is case-sensitive.
Whether plain text comparison is case-sensitive depends on the database and the column's collation. PostgreSQL and SQLite compare text case-sensitively by default. MySQL with its default collations does not. The same DISTINCT query can therefore return different row counts on different systems.
Choosing a different grain
The set of columns in your select list defines the grain of the result. The grain is what one output row represents. SELECT DISTINCT country, city has the grain "one row per country and city". Choosing the grain first makes DISTINCT easy to reason about:
- Decide what one output row should represent.
- Select exactly the columns that identify that thing.
- Add
DISTINCTonly if the source rows can repeat that combination.
For example, to list which cities have at least one customer, the grain is the city within a country. Selecting only city would merge two different cities that share a name, such as Paris in France and Paris in Texas. Selecting country, city keeps them apart.
DISTINCT with joins
DISTINCT is often added after a join produces duplicates. Suppose each customer can have many orders:
SELECT DISTINCT c.country, c.city
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id;This lists each location that has placed at least one order. Without DISTINCT, a customer with ten orders would repeat their location ten times.
Be careful here. If the duplicates come from a join that matches more rows than you intended, DISTINCT hides the symptom without fixing the cause. It also costs extra work, because the database must deduplicate the whole joined result. When you only need to know whether a match exists, an EXISTS subquery avoids creating the duplicates at all.
DISTINCT is not per column
You cannot ask for distinct values in one column while keeping other columns untouched. This query is a common attempt:
SELECT DISTINCT country, customer_id
FROM customers;The writer hoped for one row per country plus some customer. The result is one row per (country, customer_id) pair, which is every customer. To get one row per country with some other value, you need an aggregate or a window function, which are outside this chapter. For example, GROUP BY country with MIN(customer_id) returns the lowest customer ID in each country.
Some databases offer extensions for this. PostgreSQL has DISTINCT ON (country), which keeps the first row for each country according to ORDER BY. That is a PostgreSQL-specific feature. Do not rely on it if you need portable SQL.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Duplicates remain after adding `DISTINCT` | A unique column such as an ID is in the select list | Remove it or aggregate instead |
| Row count differs between databases | Different text collation and case rules | Normalize with `UPPER` or `LOWER`, or set the collation |
| Output order changes between runs | No `ORDER BY` | Add `ORDER BY` on the columns you care about |
| Query is slow with `DISTINCT` | Large joined result being deduplicated | Fix the join or use `EXISTS` |
| `DISTINCT` seems to affect only the first column | Misreading the syntax | Remember it applies to the whole select list |
Parentheses do not change the meaning
Some people write SELECT DISTINCT(country), city FROM customers. This looks like a function call on country, but the parentheses only group the expression. Databases treat it exactly like SELECT DISTINCT country, city. Avoid the style, because it suggests behavior that does not exist.
Exercise
A table employees has columns department, job_title, and employee_id. You want a list of each unique department and job title combination. A colleague writes SELECT DISTINCT department, job_title, employee_id FROM employees; and says it still shows repeats of department and job title. Why, and how do you fix it?
Show answer
DISTINCT compares whole rows, and employee_id is unique for each employee, so every row is already different and nothing is removed. Remove employee_id from the select list: SELECT DISTINCT department, job_title FROM employees ORDER BY department, job_title;. Each department and job title pair then appears once.
Exercise
The customers table has the rows (France, Paris), (France, Paris), (France, Lyon), and (Germany, Paris). How many rows does SELECT DISTINCT city FROM customers; return, and how many does SELECT DISTINCT country, city FROM customers; return?
Show answer
The first query returns 2 rows (Paris and Lyon). The second returns 3 rows: (France, Paris), (France, Lyon), and (Germany, Paris). Adding country separates the two Paris entries because they belong to different countries.