DISTINCT example
We want to know which cities appear in the table customers:
SELECT DISTINCT city
FROM customers
ORDER BY city;London appears in several rows of the table, but only once in the result. ORDER BY does not remove duplicates: it simply shows the unique values in a predictable order.
Check the result with small data
Three customers live in just two cities.
WITH customers(name, city) AS (
VALUES ('Amy', 'London'), ('Liam', 'London'), ('Eva', 'Leeds')
)
SELECT DISTINCT city FROM customers ORDER BY city;| city |
|---|
| Leeds |
| London |
DISTINCT removes repeated rows from the selected result. It does not remove customers from the table or change their addresses.
Check your understanding: What would happen if you selected DISTINCT name, city instead of just city?
Show answer
Repeated pairs of name and city would be removed. Since the three names are different, all three rows would come back even though London repeats.
What changes from case to case
DISTINCT applies to every selected expression. With one column it compares that column; with several, it compares the whole combination.
SELECT DISTINCT column_1, column_2
FROM table_name;Two rows count as repeated when the selected expressions cannot tell them apart. That is why SELECT DISTINCT city, active can return two rows for London: one for active customers and one for inactive ones.
NULL follows a special rule when removing duplicates: mainstream engines treat two NULL in the same position as not distinct for this purpose, and SQLite documents this explicitly. That does not mean an ordinary comparison NULL = NULL is true in a WHERE.
Do not use DISTINCT as a quick patch. If a combination with JOIN returns more rows than expected, check the relationship and the join condition first. Removing duplicates can hide a bug without fixing it.
Common mix-ups with DISTINCT
Expecting DISTINCT to apply to one column only
In SELECT DISTINCT city, name, almost every combination of city and name is different. If you only need the cities, select just city. Decide first what one row of the result should represent.