SQL DISTINCT
The SQL DISTINCT clause works in conjunction with the SQL SELECT clause and selects only distinct (unique) data from a database table(s). Here is an example of SQL DISTINCT clause:
As you can see the DISTINCT keyword goes immediately after the SELECT clause and is then followed by a list of one or more column names. I'll give you an example why you might need to use the DISTINCT SQL clause. I'll use the Weather table from the SQL WHERE tutorial to demonstrate the SQL DISTINCT application:
City | AverageTemperature | Date |
New York | 22 C | 10/10/2005 |
Seattle | 21 C | 10/10/2005 |
Washington | 20 C | 10/10/2005 |
New York | 18 C | 10/09/2005 |
Seattle | 20 C | 10/09/2005 |
Washington | 17 C | 10/09/2005 |
Consider the following SQL statement utilizing SQL DISTINCT:
This SQL DISTINCT expression will return a list with all cities found in the City column of the Weather table, but it will remove the duplicates and leave only a single entry for each city:
City |
New York |
Seattle |
Washington |
You can use the SQL DISTINCT with any table column for example with the AverageTemperature:
The result of this SQL DISTINCT will be:
AverageTemperature |
22 C |
21 C |
20 C |
18 C |
17 C |
You can use the SQL DISTINCT with more than one column and if you do that, the result will have all distinct combinations of values for all columns. For example if our Weather table has the following entries:
City | AverageTemperature | Date |
New York | 22 C | 10/10/2005 |
New York | 22 C | 10/09/2005 |
New York | 20 C | 10/08/2005 |
New York | 20 C | 10/07/2005 |
New York | 18 C | 10/06/2005 |
And we run the following SQL DISTINCT statement:
The result will be:
City | AverageTemperature |
New York | 22 C |
New York | 20 C |
New York | 18 C |