The SELECT DISTINCT statement is used to return only distinct (different) values from a column.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the unique values.
SELECT DISTINCT column1, column2, ... FROM table_name;
Below is a selection from the Customers table used in the examples:
Customers Table:
| CustomerID | CustomerName | Country |
|---|---|---|
| 1 | Alfreds Futterkiste | Germany |
| 2 | Ana Trujillo Emparedados | Mexico |
| 3 | Antonio Moreno Taquería | Mexico |
| 4 | Around the Horn | UK |
| 5 | Berglunds snabbköp | Sweden |
| 6 | Blauer See Delikatessen | Germany |
SELECT DISTINCT on a Single ColumnThe following SQL statement selects only the unique values from the Country column in the Customers table.
SELECT DISTINCT Country FROM Customers;
While the table has 6 records with countries "Germany", "Mexico", "Mexico", "UK", "Sweden", and "Germany", the result set from this query would only contain 4 records:
| Country |
|---|
| Germany |
| Mexico |
| UK |
| Sweden |
COUNT(DISTINCT ...)The following SQL statement shows how to use DISTINCT with an aggregate function like COUNT() to count the number of unique countries.
SELECT COUNT(DISTINCT Country) FROM Customers;
This query would return a single value: 4.
Note: We will cover the
COUNT()function in more detail in a later chapter.