• subscribe
March 27, 2002 12:00 AM

DISTINCT vs. GROUP BY

SQL Server Pro
InstantDoc ID #24282

Should I use DISTINCT or GROUP BY to eliminate duplicates in a result set?

A DISTINCT and GROUP BY usually generate the same query plan, so performance should be the same across both query constructs. For example, say you want to generate a unique list of product IDs from the Order Details table in Northwind. The two following queries both give you a correct answer:

SELECT DISTINCT od.productid
FROM [order details] OD
SELECT od.productid
FROM [order details] OD
GROUP BY od.productid

Which one is more efficient? Checking execution plans is a simple way to determine the relative efficiency of different queries that generate the same result set. Enable Show Execution Plan in Query Analyzer by pressing Ctrl+K or by selecting Show Execution Plan from the Query menu. Then, execute the above queries. Figure 1 shows that the execution plans of both queries are the same. In most cases, DISTINCT and GROUP BY generate the same plans, and their performance is usually identical.

So, how do you decide which SQL command to use? GROUP BY is required if you're aggregating data, but in many cases, DISTINCT is simpler to write and read if you aren't aggregating data. Pick whichever syntax you prefer for your situation.



ARTICLE TOOLS

Comments
  • Mike
    7 years ago
    Dec 19, 2005

    Isn't using a DISTINCT a sign of a faulty query? Whenever I create a query, I run it with and without a DISTINCT and, if there is a difference in the record count in the result, I try to figure out why. Usually, if the record counts are different, there is something you hadn'tconsidered.

You must log on before posting a comment.

Are you a new visitor? Register Here
  • SP1?
    I know there is a SP1 for SQL 2008 R2 available....and there is a "feature pack" as well... ...
  • SQL database mirroring
    I have SQL Server 2008 R2 Enterprise 64bit on Windows 2008 R2 Enterprise 64bit.  Each SQL Server has...
  • Dell Compellent Disk Drive
    Does anybody has experience with Dell Compellent Disk Drive? Basically, this system manages all disk...
  • Sql server performance tuning
    I need to find a tool that help me to optimize sql server,queries,improve the performance and solve ...