SQL tutorial

SQL Select Distinct

Learn more about SQL, a standard language for interacting with databases and storing, manipulating, and retrieving data from databases.

Go hands-on with SQL in our free interactive SQL tutorial.

The DISTINCT keyword in SQL is applied to a SELECT statement to modify its behavior and return only unique records in the result.

For example, let’s say we wrote a query to return the first names from the employees table. We would get a record returned for every row in the table, which would include duplicates if there were multiple employees with the same first name:

Code Example
SELECT first_name FROM employees;

We can see this even more clearly if we also return the employee last names sort the results of the query alphabetically by first name using ORDER BY:

Code Example
SELECT first_name FROM employees ORDER BY first_name ASC;
first_namelast_name
AamerJayawardene
AamerGlowinski
AamerKornyak
AamerParveen
AamerSzmurlo
AamerGarrabrants
AamerTsukuda
AamerFraisse
AamerKroll
AamerSlutz

Clearly, there are many employees with the same first name. If we wanted to return all the unique first names from the table, we can simply add the DISTINCT clause to our original query. The DISTINCT clause is placed before the columns to be returned in a SELECT statement as below:

Code Example
SELECT DISTINCT <columns> FROM <table>;

Therefore our original query becomes the below, and returns only the unique values in first_name column in the employees table:

Code Example
SELECT DISTINCT first_name FROM employees;
first_name
Georgi
Bezalel
Parto
Chirstian
Kyoichi

While our original query returned over 300K results (one first name for each employee), the above returns the distinct first names in the table of which there are only 1275.

Learn SQL Today

Get hands-on experience writing code with interactive tutorials in our free online learning platform.

  • Free and fun
  • Designed for beginners
  • No downloads or setup required