fbpx

DISTINCT

What if you were given the following table of colors...

colors
red
orange
red
blue
blue
blue
red
blue

...and asked to write a query to list out all the unique colors. In other words... remove any duplicates?

We'd use the DISTINCT keyword in our SELECT statement!

The DISTINCT keyword goes at the start of your SELECT statement and returns the unique values from a field. In other words, it removes any duplicates.

How to use DISTINCT

If we wanted to write a query that listed all the colors in the table as-is, without removing duplicates, we'd write the following:

SELECT colors
FROM color_database.colors_table;

(Ignore the FROM statement, it's not critical to learning DISTINCT.)

This would display the following output:

Query Output

colors
red
orange
red
blue
blue
blue
red
blue

Now... how can we use the DISTINCT keyword here to remove duplicates?

All we've gotta do is place it right after "SELECT"...

SELECT DISTINCT colors
FROM color_database.colors_table;

...resulting in the following output, with duplicates removed!

Query Output

colors
red
orange
blue

This shows us that the unique colors in the colors field are red, orange, & blue!