Saturday, December 22, 2012

DISTINCT Keyword

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

Result
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

Result
Employee NameSalary
Garima Khanna70000
Varun Khanna75000

Hope this article gives some basic understanding of DISTINCT keyword.

Difference between Function and Stored Procedure

Today, i am listing down just the basic difference between Function and Stored Procedure often asked in interviews.




Function Stored Procedure
1 Function always needs to return the value Stored Procedure may or may not return the value
2 Function can be called from within the Stored Procedure Stored Procedure cannot be called from Function
3 Function cannot have any DML statement i.e. it cannot be used for Data Manipulation in Tables Stored Procedure can have DML statements i.e. it can be used to perform Data Manipulation in Tables
4 Function cannot have an output parameter Stored Procedure may or maynot have an output parameter defined
5 Function can be called directly in Select statement Stored Procedure can be called using EXEC or EXECUTE keyword


Hope this helps !!