Learn SQL: DISTINCT
Removing duplicates with DISTINCT
"The mayor wants to know which towns our visitors come from," says Noor. "But my list names Hasselt six times." Once is enough.
DISTINCT keeps each row once
Put DISTINCT right after SELECT and each row appears only once in the result, however often it is in the table.
Below you see the same column without DISTINCT: eighteen tickets, with plenty of duplicates.
SELECT DISTINCT town FROM tickets| town |
|---|
| Hasselt |
| Genk |
| Antwerpen |
| Leuven |
| Maastricht |
| Sint-Truiden |
| Tongeren |
SELECT town FROM tickets| town |
|---|
| Hasselt |
| Genk |
| Hasselt |
| Antwerpen |
| Leuven |
| Maastricht |
| Hasselt |
| Genk |
A duplicate is the whole row
With several columns, DISTINCT looks at the combination. A day ticket for Friday and a day ticket for Saturday are two different rows.
Here NULL counts as one value: none of the combi tickets has a day, so they appear only once in the result.
SELECT DISTINCT kind, day FROM tickets| kind | day |
|---|---|
| combi ticket | NULL |
| day ticket | 2025-07-19 |
| day ticket | 2025-07-18 |
| vip | 2025-07-19 |
| day ticket | 2025-07-20 |
| vip | 2025-07-18 |
| vip | 2025-07-20 |
Try it yourself
For which days were day tickets sold? Show each day once, the earliest first.
Ready for more?
The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.
Start the lesson