SQL SELECT DISTINCT
A column often contains the same value many times — 25 customers live in only 20 countries. SELECT DISTINCT removes duplicate rows from the result so each combination appears once.
SELECT DISTINCT column1, column2, ...
FROM table_name;Duplicates without DISTINCT
SELECT country
FROM customers
WHERE country IN ('USA', 'UK', 'Canada', 'Spain')
ORDER BY country;country
-------
Canada
Canada
Spain
UK
UK
USA
USA
(7 rows)
USA, UK and Canada each show up twice, because two customers live there.
Removing duplicates
SELECT DISTINCT country
FROM customers
WHERE country IN ('USA', 'UK', 'Canada', 'Spain')
ORDER BY country;country
-------
Canada
Spain
UK
USA
(4 rows)
DISTINCT works on whole rows
With several columns, DISTINCT looks at the combination of values. Two rows are duplicates only when every selected column matches:
SELECT DISTINCT customer_id, status
FROM orders
WHERE customer_id IN (17, 18)
ORDER BY customer_id, status;customer_id | status
------------+-----------
17 | delivered
17 | shipped
18 | cancelled
18 | delivered
18 | processing
(5 rows)
Customer 18 has several delivered orders, but the pair (18, delivered) appears only once.
Counting distinct values
Combine DISTINCT with COUNT to ask "how many different …?":
SELECT COUNT(country) AS countries_listed,
COUNT(DISTINCT country) AS different_countries
FROM customers;
SELECT COUNT(DISTINCT customer_id) AS customers_who_ordered
FROM orders;countries_listed | different_countries
-----------------+--------------------
25 | 20
(1 row)
customers_who_ordered
---------------------
18
(1 row)
The 40 orders were placed by only 18 different customers, and the 25 customers come from 20 different countries.
Note:
DISTINCTtreats allNULLvalues as equal, so several NULLs collapse into one row in the result.COUNT(DISTINCT col)ignores NULLs entirely.
DISTINCT vs GROUP BY
SELECT DISTINCT status FROM orders gives the same rows as SELECT status FROM orders GROUP BY status. Use DISTINCT when you only want the unique values; use GROUP BY (covered later) when you also want to count or sum per value.
| Database | Notes |
|---|---|
| SQLite, MySQL, SQL Server | SELECT DISTINCT, COUNT(DISTINCT col) |
| PostgreSQL | also DISTINCT ON (col) to keep the first row per value |
| MS Access | no COUNT(DISTINCT …); use a subquery |
Tip:
DISTINCThas to compare all result rows, so it costs some work on big tables. If you get unexpected duplicates from a join, fix the join instead of hiding the problem withDISTINCT.
Test yourself
What does SELECT DISTINCT city, country FROM customers remove?
- Rows where city is duplicated
- Rows where country is duplicated
- Rows where both city and country are the same as another row
- Nothing
Which query counts how many different statuses orders have?
- SELECT COUNT(status) FROM orders
- SELECT DISTINCT COUNT(status) FROM orders
- SELECT COUNT(DISTINCT status) FROM orders
- SELECT UNIQUE(status) FROM orders