Sunday, February 10, 2013

How to use SELECT DISTINCT in SQL Server

SELECT DISTINCT Statement in SQL Server
The SQL DISTINCT Statement is used to list out only the Distinct Records from a Table which may be contains duplicate values.
The DISTINCT keyword can be used to return only distinct (different) values ,which means that it will only return unique/no duplicate values from the selected Columns/from a Table.
Syntax:
SELECT DISTINCT column_name(s) FROM Table_name

Example:

Suppose we have an EMP Table , with out a primary key / constraints with duplicate records(1004) as follows :
Emp_ID
E_Name
Job
Dept_ID
Salary
1001
Ravi Teja Reddy
Analyst
1
20000
1003
Ravi Kumar Rao
Analyst
1
10000
1004
Smith
Team Lead
3
50000
1005
Sai Kumar Teja
Analyst
2
15000
1006
William
Manager
3
50000
1007
Vikram Teja Reddy
Analyst
2
18000
1004
Smith
Team Lead
3
50000
---------------------------------------------------------------
Criteria-I :
 From the above Table we can select only distinct records using the DISTINCT Keyword as follows :
SELECT DISTINCT *From EMP

Result :
Emp_ID
E_Name
Job
Dept_ID
Salary
1001
Ravi Teja Reddy
Analyst
1
20000
1003
Ravi Kumar Rao
Analyst
1
10000
1004
Smith
Team Lead
3
50000
1005
Sai Kumar Teja
Analyst
2
15000
1006
William
Manager
3
50000
1007
Vikram Teja Reddy
Analyst
2
18000
---------------------------------------------------------------
Criteria-II :
 From the above Table we can select only distinct Job types using the DISTINCT Keyword as follows:
SELECT DISTINCT Job FROM EMP_MAIN

Result :
JOB
Analyst
Manager
Team Lead

--------------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.