#0332 – SQL Server – Myths – Is DISTINCT faster than GROUP BY?


I have often seen a recommendation that using DISTINCT instead of GROUP BY is better from a performance perspective. DISTINCT is definitely a more readable alternative, but I wanted to test for myself as to what the truth was.


To compare the performance of the two, I wrote the following simple queries.


The query below helps in identifying the number of records that SQL Server will need to process. On my machine, when executed without the GROUP BY or the DISTINCT clause, the query generates records in excess of 380,000.

USE AdventureWorks2012;
GO
SELECT COUNT(so1.object_id)
FROM sys.objects AS so1
CROSS JOIN sys.objects AS so2 ;
GO

The queries below fetch the same information – one uses the GROUP BY whereas the other query uses a DISTINCT.

USE AdventureWorks2012;
GO
–Clean the buffers and procedure cache
DBCC DROPCLEANBUFFERS;
DBCC FREEPROCCACHE;
GO

–Evaluate GROUP BY
SELECT so1.object_id,
so1.name
FROM sys.objects AS so1
CROSS JOIN sys.objects AS so2
GROUP BY so1.object_id, so1.name ;
GO

–Clean the buffers and procedure cache
DBCC DROPCLEANBUFFERS;
DBCC FREEPROCCACHE;
GO

–Evaluate DISTINCT
SELECT DISTINCT
so1.object_id,
so1.name
FROM sys.objects AS so1
CROSS JOIN sys.objects AS so2 ;
GO


Before executing the two queries (one with the GROUP BY and the other with the DISTINCT), I had turned on the actual execution plan.


image


Upon studying the execution plan, the following observations can be made:



  1. When the SQL server database engine detected that the 2nd query did not have any aggregation function, it was smart enough to convert the GROUP BY into a DISTINCT when the query plan is generated
  2. There is no difference in the execution plan across both the queries

In conclusion,



DISTINCT is not faster than GROUP BY. In fact, Both DISTINCT and GROUP BY demonstrate equal performance impact.


When aggregations are not being used, DISTINCT is more readable when compared to GROUP BY.


Until we meet next time,



Be courteous. Drive responsibly.

Advertisement

Let me know what you think about this post by leaving your feedback here!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.