SQL SELECT DISTINCT

SQL SELECT DISTINCT Explanation

SELECT DISTINCT returns only unique (i.e. distinct) values.

SELECT DISTINCT eliminates duplicate values from the results.

DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.

DISTINCT operates on a single column.

DISTINCT for multiple columns is not supported.

Example

#

Problem: List the unique cities that French customers are from.

SELECT DISTINCT City
  FROM Customer
 WHERE Country = 'France'

Syntax

DISTINCT syntax.

SELECT DISTINCT column-name
  FROM table-name

DISTINCT syntax with COUNT or other aggregates.

SELECT COUNT (DISTINCT column-name)
  FROM table-name

More Examples

SELECT DISTINCT

SUPPLIER
Id
CompanyName
ContactName
City
Country
Phone
Fax
Problem: List all unique supplier countries in alphabetical order.
SELECT DISTINCT Country
  FROM Supplier
ORDER BY COUNTRY
Result: 16 rows
Country
Australia
Brazil
Canada
Denmark

SELECT COUNT DISTINCT

SUPPLIER
Id
CompanyName
ContactName
City
Country
Phone
Fax
Problem: Count the number of unique supplier countries.
SELECT COUNT (DISTINCT Country) AS Number
  FROM Supplier
Result:
Number
16

You may also like



Guides