SQL Tutorial

SQL Select Distinct

The SQL SELECT DISTINCT Statement

To retrieve just distinct (different) data, use the SELECT DISTINCT command.

Example

Select all the different countries from the “Customers” table:

				
					SELECT DISTINCT Country FROM Customers;
				
			

A column in a database may have a lot of duplicate entries, and there may be instances when you just want to list the unique values.

Syntax

SELECT DISTINCT column1, column2, …

FROM table_name;

Demo Database

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

The SQL statement returns the “Country” value from each record in the “Customers” table if the DISTINCT clause is left out:

Example

				
					SELECT Country FROM Customers;
				
			

Count Distinct

We may retrieve the total number of distinct countries by utilizing the DISTINCT keyword in the COUNT function.

Example

				
					SELECT COUNT(DISTINCT Country) FROM Customers;
				
			

Note: Microsoft Access databases do not support COUNT(DISTINCT column_name).

An MS Access workaround is provided here:

Example

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

The COUNT function will be covered later in this tutorial.

Share this Doc

SQL Select Distinct

Or copy link

Explore Topic