SQL SELECT DISTINCT

The SQL SELECT DISTINCT Statement

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.


Syntax

SELECT DISTINCT column1, column2, ...
FROM table_name;

Demo Database

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

Example 1: SELECT DISTINCT on a Single Column

The following SQL statement selects only the unique values from the Country column in the Customers table.

DISTINCT Example

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

Example 2: COUNT(DISTINCT ...)

The following SQL statement shows how to use DISTINCT with an aggregate function like COUNT() to count the number of unique countries.

COUNT(DISTINCT) Example

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.