SQL SELECT DISTINCT Statement
The SELECT DISTINCT
statement in SQL is used to retrieve only unique values from one or more columns in a table. It removes duplicate rows from the result set, giving you a concise list of distinct entries.
SELECT DISTINCT: Definition and Usage
SELECT DISTINCT
is incredibly useful when you only need a list of unique values and don't want to see repeated entries. This is commonly used when you want a list of all available options for a particular column (for example: unique countries, product categories, or any other attribute where you're interested only in the distinct values).
Syntax
Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
Example Database
Let's use a sample 'Customers' table for our examples:
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 |
Examples
Selecting Distinct Countries
This query retrieves a list of unique countries from the 'Customers' table.
Syntax
SELECT DISTINCT Country FROM Customers;
Output
Country
-------
Germany
Mexico
UK
Sweden
Selecting All Countries (Without DISTINCT)
This query, without DISTINCT
, returns all countries, including duplicates.
Syntax
SELECT Country FROM Customers;
Output
Country
-------
Germany
Mexico
Mexico
UK
Sweden
Counting Distinct Countries
This uses COUNT(DISTINCT)
to get the number of unique countries. (Note: COUNT(DISTINCT)
is not supported by MS Access.)
Syntax (Most SQL Databases)
SELECT COUNT(DISTINCT Country) FROM Customers;
Syntax (MS Access Workaround)
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
Output
DistinctCountries
-----------------
4