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.
|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:
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:
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:
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: