Monday, August 29, 2011

SQL Distinct Command


The SQL DISTINCT clause is used together with the SQL SELECT keyword, to return a dataset with unique entries for certain database table column.
 
Example query using Company table for SQL DISTINCT.

FirstName
LastName
Email
DOB
Phone
Scott
Armstrong
Armstrong.yahoo.com
2/4/1968
887-676-2321
Adam
Red
red@himail.com
4/4/1978
792 343-2422
Santo
Harry
Harry@livingin.org
5/24/1978
416 323-3232
Jackson
Jimmy
Jimmy@supermail.co.uk
20/10/1980
416 323-8888


For example if we want to select all distinct surnames from our Company table, we will use the following SQL DISTINCT statement:


SELECT DISTINCT LastName
FROM Company

The result of the SQL DISTINCT expression above will look like this:
LastName
Armstrong
Red
Harry
Jimmy
Because lastname Does not Include any duplicate values all the cells of Lastname wil be included.

The second example i am posting using adventure works database which is sample database from microsoft and can be downloaded from www.codeproject.com for free and can be installed in microsoft sql server 2005/2008.



Select SalesOrderID from Sales.SalesOrderDetail

Select distinct SalesOrderID from Sales.SalesOrderDetail

 The first query will return all the SalesOrderID's but second will return distinct SalesOrderID's reducing the number and duplicate values.

MORE BASIC SQL COMMANDS

1 comment: