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.
CarMake | Model | Year | Color |
Toyota | Camry XLE | 2005 | Gray |
Honda | Accord EX | 2002 | Black |
Lexus | ES 350 | 2008 | Gray |
BMW | 3 Series Coupe | 2008 | Red |
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:
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:
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:
The result of the SQL query above will look like this:
Year | Color |
2005 | Gray |
2002 | Black |
2008 | Gray |
2008 | Red |
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:
Year | Color |
2005 | Gray |
2008 | Gray |
and
Year | Color |
2008 | Gray |
2008 | Red |