SELECT DISTINCT
A table often contains duplicate values in a column — many customers might live in the same city, many orders might share the same status. The
DISTINCT keyword removes duplicate rows from a result set, leaving only unique combinations behind.Removing duplicate values
Unique cities
SQL
SELECT DISTINCT city FROM customers;
If ten customers live in Toronto and five live in Ottawa, this query returns
Toronto and Ottawa exactly once each, no matter how many rows share those values in the underlying table.DISTINCT across multiple columns
When you apply
DISTINCT to more than one column, it does not deduplicate each column separately — it treats the combination of all the listed columns as a single unit and returns each unique combination once.Unique city and country combinations
SQL
SELECT DISTINCT city, country FROM customers;
A common misunderstanding
Given rows
(Toronto, Canada), (Toronto, Canada), and (Toronto, USA) — the last one being a data entry quirk — this query returns two rows: (Toronto, Canada) and (Toronto, USA). The row is only dropped when *both* columns together match a row already seen, not when just the city matches.Counting unique values
To count how many distinct values exist rather than list them, wrap the column in
COUNT(DISTINCT ...):Count unique cities
SQL
SELECT COUNT(DISTINCT city) AS unique_cities FROM customers;
This is very different from plain
COUNT(city), which counts every non-null row regardless of duplicates.Performance consideration
DISTINCT is not free. To find duplicates, the database generally has to compare or sort every row in the result set (or build a hash of the rows it has seen so far) before it can hand you a deduplicated answer. On a large result set this can be noticeably slower than an equivalent query without DISTINCT, so it is worth asking whether the duplicates are actually a problem, or whether a more specific WHERE clause or a GROUP BY would answer the real question more efficiently.