Saturday, March 12, 2016

SQL DISTINCT Command

SQL DISTINCT COMMAND

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:

 SELECT DISTINCT Column1 FROM Table1

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:

CityAverageTemperatureDate
New York22 C10/10/2005
Seattle21 C10/10/2005
Washington20 C10/10/2005
New York18 C10/09/2005
Seattle20 C10/09/2005
Washington17 C10/09/2005

Consider the following SQL statement utilizing SQL DISTINCT:

 SELECT DISTINCT City  FROM Weather 


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:

 SELECT DISTINCT AverageTemperature  FROM Weather 


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:

CityAverageTemperatureDate
New York22 C10/10/2005
New York22 C10/09/2005
New York20 C10/08/2005
New York20 C10/07/2005
New York18 C10/06/2005

And we run the following SQL DISTINCT statement:

 SELECT DISTINCT City, AverageTemperature  FROM Weather 


The result will be:
CityAverageTemperature
New York22 C
New York20 C
New York18 C

0 comments:

Post a Comment

 
Animated Social Gadget - Blogger And Wordpress Tips