The SELECT DISTINCT
statement is used to return only distinct (different) values.
Retrieve the distinct countries listed in the “Customers” table.
SELECT DISTINCT Country FROM Customers; |
In a table, a column frequently comprises numerous repetitive values; occasionally, you may seek to display only the unique (distinct) values.
SELECT DISTINCT column1, column2, ... |
Here is a segment from the Customers table employed in the illustrations:
CustomerID |
CustomerName |
ContactName |
Address |
City |
PostalCode |
Country |
1 |
Alfreds Futterkiste |
Maria Anders |
Obere Str. 57 |
Berlin |
12209 |
Germany |
2 |
Ana Trujillo Emparedados y helados |
Ana Trujillo |
Avda. de la Constitución 2222 |
México D.F. |
05021 |
Mexico |
3 |
Antonio Moreno Taquería |
Antonio Moreno |
Mataderos 2312 |
México D.F. |
05023 |
Mexico |
4 |
Around the Horn |
Thomas Hardy |
120 Hanover Sq. |
London |
WA1 1DP |
UK |
5 |
Berglunds snabbköp |
Christina Berglund |
Berguvsvägen 8 |
Luleå |
S-958 22 |
Sweden |
Without including the DISTINCT keyword, the SQL query will retrieve the “Country” value from every record in the “Customers” table.
SELECT Country FROM Customers; |
Employing the DISTINCT keyword within the COUNT function allows us to retrieve the count of unique countries.
SELECT COUNT(DISTINCT Country) FROM Customers; |
Please note that the COUNT(DISTINCT column_name) function is not compatible with Microsoft Access databases. |
Here is a workaround for MS Access:
SELECT Count(*) AS DistinctCountries FROM (SELECT DISTINCT Country FROM Customers); |
Later in this tutorial, you’ll gain insight into the COUNT function.