SQL DISTINCT: list each value only once

DISTINCT removes duplicate rows from a query result. It is the quickest way to see which cities, categories or order statuses actually exist, instead of scrolling past the same value twenty times.

In short: SELECT DISTINCT city FROM customers; returns every city once. DISTINCT goes right after SELECT and always applies to the whole row: with several columns, a row is only dropped when it matches another row in every column.

What you should know first: picking columns with SELECT. The part about missing values builds on the NULL lesson.

Try it now

The customers table has twelve rows, but some cities appear more than once. Marketing only wants to know which cities are on the list.

Task Marketing is planning a mailing per city and wants to know which cities the shop has customers in at all. From the customers table, get the city column, each city only once.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164

How DISTINCT works

The orders table has 18 rows, each with a status. SELECT status FROM orders therefore returns 18 rows, and "delivered" alone shows up eleven times. Add DISTINCT and you get the short version:

SELECT DISTINCT status
FROM orders;
status
delivered
cancelled
shipped
open

The database first builds the result as if DISTINCT were not there, then throws away every row it has already seen. The table itself stays as it is. If you have used Remove Duplicates in a spreadsheet, it is the same idea, except your data is never touched.

Row order is not guaranteed. For a sorted list, add ORDER BY from the ORDER BY lesson: SELECT DISTINCT category FROM products ORDER BY category; lists the six categories from Electronics to Writing.

DISTINCT on multiple columns

With two columns after DISTINCT, the database compares the combination. SELECT DISTINCT country, segment FROM customers lists USA several times: once with Business, once with Consumer, once with Government and once with School. A row only counts as a duplicate when country and segment both match.

That leads to a rule worth remembering: every column you add makes the result longer. SELECT DISTINCT city, name brings back all twelve customers, because no two customers share a name. DISTINCT can only remove rows that are identical across every column.

Practice: combinations

Two columns this time. Before you run it, guess roughly how many rows you expect.

Task For campaign planning, sales needs every combination of country and customer segment that exists in the customer base. Get the columns country and segment, in that order, with each combination only once.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164

DISTINCT and NULL

Three consumer customers have no phone number, so their phone column is NULL. What does DISTINCT do with them?

SELECT DISTINCT phone
FROM customers
WHERE segment = 'Consumer';
phone
NULL
0113 496 0123
617-555-0199

Five consumers, three rows: the three missing numbers collapse into a single NULL row. For DISTINCT, two NULLs count as the same. That may surprise you, because in a WHERE clause NULL = NULL is never true. DISTINCT uses a different test: two values are duplicates when you cannot tell them apart, and two unknowns look exactly alike.

If you don't want the NULL row, filter it out first with WHERE phone IS NOT NULL.

Looking ahead: DISTINCT or GROUP BY?

Level 2 introduces GROUP BY. SELECT city FROM customers GROUP BY city returns the same list as DISTINCT. The difference is what comes next: GROUP BY builds groups you can calculate with, such as the number of customers per city, while DISTINCT only removes repeats. When all you need is the list of values, DISTINCT says it more plainly.

Common mistakes

Forgetting DISTINCT

Without it, every row comes back and the cities repeat. The exercise then says "Your query returns 12 rows. Wanted: 9 rows." Too many rows with repeated values point to a missing DISTINCT.

One column too many

Adding the name "just to check", as in SELECT DISTINCT city, name, cancels DISTINCT out, because each row is unique again. The exercise reports "Your query returns 2 columns. Wanted: 1 column, namely city."

DISTINCT in front of every column

SELECT DISTINCT country, DISTINCT segment is a syntax error. DISTINCT appears once, right after SELECT, and covers every column. The exercise tells you exactly that.

Parentheses that do nothing

SELECT DISTINCT(country), segment looks as if DISTINCT applied to country only. The parentheses just wrap the column and change nothing: the result is the same as SELECT DISTINCT country, segment. Leave them out so nobody reads more into the query than is there.

DISTINCT in MySQL, PostgreSQL, SQL Server and SQLite

SELECT DISTINCT behaves the same in all four. The differences are in the extras:

DatabaseWorth knowing
MySQLDISTINCTROW is another name for DISTINCT.
PostgreSQLAlso has DISTINCT ON (column), which keeps only the first row for each value of that column; ORDER BY decides which row is first. The manual states that NULLs count as equal.
SQL ServerThe documentation states that NULL values are equal for DISTINCT. DISTINCT comes before TOP: SELECT DISTINCT TOP (5) city …
SQLite (these exercises)Compares rows with IS DISTINCT FROM, so two NULLs are equal. Text is compared using the column's collation, which is exact by default: "Boston" and "boston" are two different values.

FAQ

Does DISTINCT only apply to the first column?

No. DISTINCT always applies to all the columns in the result together. A row is only removed when it matches another row in every column.

Does DISTINCT sort the result?

Not reliably. The output sometimes looks sorted because of how the database does the work internally, but nothing guarantees it. If order matters, add ORDER BY at the end.

How do I count how many different cities there are?

With COUNT(DISTINCT city). COUNT and the other functions for counting and totals open level 2.

Can I combine DISTINCT with WHERE?

Yes. WHERE filters the rows first, then DISTINCT removes the repeats. SELECT DISTINCT city FROM customers WHERE segment = 'Business' lists every city with at least one business customer.

My query suddenly returns duplicate rows. Should I just add DISTINCT?

Find out where they come from first. Once you join several tables, duplicates often point to a mistake in the join, and DISTINCT only hides it. On a single table like here, though, DISTINCT is exactly the right tool.

Up next: calculations in SQL

So far you have shown values exactly as they are stored. Next you calculate with them: stock value from price times quantity, sale prices, rounding, and column names of your own choosing.

Practice SQL calculations

Write to us

Choose language

Select your preferred language