SQL DISTINCT

In the first chapter we discussed the SELECT command, and now it's time to learn about another important SQL keyword, which is used along with SELECT - the DISTINCT keyword.

The DISTINCT is used to select only unique values from a specified column in a database table. We will use our Cars table to illustrate how does DISTINCT work.

CarMakeModelYearColor
ToyotaCamry XLE2005Gray
HondaAccord EX2002Black
LexusES 3502008Gray
BMW3 Series Coupe2008Red

If you want to select a list of all unique colors from all rows in the table, you can accomplish it by using the following SQL statement:

SELECT DISTINCT Color FROM Cars;

The DISTINCT keyword goes right away after the SELECT keyword, and in turn is followed by the column(s) we are selecting the distinct values from. The result of the statement above is this:

Color
Black
Gray
Red

If we want to get all different years of the cars in our Cars table, we can do it as follows:

SELECT DISTINCT Year FROM Cars;

Getting this as a result:

Year
2002
2005
2008

But how can you retrieve the distinct combinations of values from more than one column, for example Year and Color columns? All you need to do in this case is to list all columns separated by commas after the DISTINCT keyword like that:

SELECT DISTINCT Year, Color FROM Cars;

The result of the SQL query above will look like this:

YearColor
2005Gray
2002Black
2008Gray
2008Red

If you look carefully the result displayed above you will notice that the Gary color appears more than once there, and the year 2008 has 2 entries as well. Even though there are duplications for both columns, the combinations between the 2 are still unique:

YearColor
2005Gray
2008Gray

and

YearColor
2008Gray
2008Red