🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

Using SQL Distinct to Exclude Duplicates

Reading time 1 min
Published Jan 5, 2016
Updated Oct 9, 2019

TL;DR – When a column contains duplicate values and you only need to list the distinct (different) ones, you can use the SELECT DISTINCT command.

Syntax of SQL SELECT DISTINCT

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

Examples using a demo database

The Developers table

ID Name City Country
1 Tom Kurkutis New York USA
2 Ana Fernandez London UK
3 Antonio Indigo Paris France
4 Aarav Kaelin Delhi India
5 Andrew Tumota Miami USA
6 Basma Zlata Miami USA
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
edX
Pros
  • A wide range of learning programs
  • University-level courses
  • Easy to navigate
  • Verified certificates
  • Free learning track available
Main Features
  • University-level courses
  • Suitable for enterprises
  • Verified certificates of completion

Selecting all values from one column

Example
SELECT City FROM Developers;

Selecting only distinct values from one column

Example
SELECT DISTINCT City FROM Developers;

Counting distinct values

Example
SELECT COUNT(DISTINCT City) FROM Developers;

Note: this example will not work in Microsoft Edge and Firefox, as they use Microsoft Access which doesn't support COUNT(DISTINCT column_name).

In MS Access

Example
SELECT Count(*) AS DistinctCities
FROM (SELECT DISTINCT City FROM Developers);