Saturday, December 22, 2012


Today, we would be discussing about the DISTINCT keyword. Often we use distinct in our SQL queries to get the distinct records.

Consider the below data present in Employee table

Employee Name Salary
Varun Khanna 50000
Garima Khanna 60000
Garima Khanna 70000
Varun Khanna 75000

If we execute below query 

SELECT distinct Employee_Name,Salary
  FROM Employees_Salary

Employee NameSalary
Garima Khanna60000
Garima Khanna70000
Varun Khanna50000
Varun Khanna75000

Now you must have expected distinct record of each employee; however this is not the case as to how DISTINCT works.

When we apply distinct in above query it doesn't search only for Employee Name; however it looks for distinct records for both Employee Name and Salary. Meaning if there have been duplicate record then it would have been shown only once.

 It is just a tag that you can put after the word SELECT to indicate that you want only distinct combinations of all columns in the result set returned.

Below are the key points

  • DISTINCT always operates on all columns in the final result
  • DISTINCT is not a function that accepts a column as an argument
We can modify the above query to return us the distinct employee Name.

Query would be 

SELECT distinct Employee_Name,max(Salary) as MaximumSalary
  FROM Employees_Salary
  group by Employee_Name

Employee NameSalary
Garima Khanna70000
Varun Khanna75000

Hope this article gives some basic understanding of DISTINCT keyword.

No comments:

Post a Comment