Curriculum
Course: SQL
Login

Curriculum

SQL

SQL References

0/80

MySQL Functions

0/139

SQL Server Functions

0/84

SQL Quick Ref

0/1
Text lesson

SQL SELECT DISTINCT

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.

Example

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.

Syntax

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

Demo Database

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

SELECT Example Without DISTINCT

Without including the DISTINCT keyword, the SQL query will retrieve the “Country” value from every record in the “Customers” table.

Example

SELECT Country FROM Customers;

Count Distinct

Employing the DISTINCT keyword within the COUNT function allows us to retrieve the count of unique countries.

Example

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:

Example

SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);

Later in this tutorial, you’ll gain insight into the COUNT function.