Monday, December 08, 2014

Difference between DISTINCT and GROUP BY – Distinct vs Group By

A DISTINCT and GROUP BY usually generate the same query plan, so performance should be the same across both query constructs. GROUP BY should be used to apply aggregate operators to each group. If all you need is to remove duplicates then use DISTINCT. If you are using sub-queries execution plan for that query varies so in that case you need to check the execution plan before making decision of which is faster.
Example of DISTINCT:
SELECT DISTINCT EmployeeRankFROM Employees
Example of GROUP BY:
SELECT EmployeeRankFROM EmployeesGROUP BY EmployeeRank
Example of GROUP BY with aggregate function:
SELECT EmployeeRankCOUNT(*) EmployeeCountFROM EmployeesGROUP BY EmployeeRank

No comments:

Post a Comment