5) SQL Commands for Querying Databases Lesson

SELECT DISTINCT

4 min to complete · By Ryan Desmond

The DISTINCT statement can be combined with the SQL SELECT statement to obtain more specific data. The SQL SELECT DISTINCT statement allows you to select rows that have unique values for specific columns.

This lesson discusses how to use DISTINCT in SQL.

Colorful illustration of a light bulb

Note: This lesson uses the MySQL Sakila demo database. If you haven't already, follow the steps to import the Sakila DB, then head back here.

How to Use Distinct in SQL

Imagine that you have multiple records with similar traits, but you would like to know the information about the unique instead of repeated values. Let's look at an example.

In the query below, you selected all the actors from the actor table and sorted the actors by first_name. (You can sort the column by first_name by simply clicking on "first_name" in the Result Grid in MySQL Workbench.)

See how there are multiple actors named "ADAM", "ALBERT", "AUDREY", "BEN", and so on?

View of the Sakila.Actor table in MySQL Workbench

But what if you just want to know the number of distinct unique names in the actor table? You can do that by using the keyword DISTINCT. For example:

SELECT DISTINCT first_name from actor;

Which will give you the following result:

Distinct first names in Sakila.Actor table

You use the SQL SELECT DISTINCT command when you want to retrieve only distinct (aka different) results. 

SQL Select Distinct Real-World Example

Here's another example of how to use SQL SELECT DISTINCT. Suppose you work in HR at a large company with 500+ employees, and you need to figure out how many days of the year it is someone's birthday so you can bring in some treats.

You don't need to know whose birthday it is or how many people have birthdays on that day. You just need to know what dates you need to bring in treats. In this case, you might run a query that looks like this:

SELECT DISTINCT birth_day, birth_month FROM employees;

The resulting dataset would then give you a list of distinct dates on which you need to bring in treats :)

Happy Birthday treats

Summary: SQL Select Distinct Statement

In this lesson, you learned how to use DISTINCT in SQL. The SQL SELECT DISTINCT statement provides the ability to select rows that have unique values for one or more columns.

SQL Select Distinct Syntax Here's the syntax for the SQL SELECT DISTINCT command, where you can substitute the variables in < > with your values.

SELECT DISTINCT <YOUR_COLUMN_NAMES> FROM <YOUR_TABLE>;

Next up is a video going over simple SELECT statements!