Lesson 5 +10 XP

SELECT DISTINCT

SELECT DISTINCT

The SELECT DISTINCT statement returns only different (unique) values.

Without DISTINCT

SELECT Country FROM Customers;

Returns every country, with duplicates (Mexico appears twice).

Country
Germany
Mexico
Mexico
UK

With DISTINCT

SELECT DISTINCT Country FROM Customers;

Returns each country only once:

Country
Germany
Mexico
UK

Multiple columns

SELECT DISTINCT Country, City FROM Customers;

Now the pair (Country, City) must be different - so Mexico/Mexico City and Mexico/Guadalajara are both kept.

Count the unique values

SELECT COUNT(DISTINCT Country) FROM Customers;

This counts how many different countries exist.

TL;DR

  • DISTINCT removes duplicate rows from the result.
  • With multiple columns, the whole row combination must be unique.
  • COUNT(DISTINCT col) counts unique values.