SELECT DISTINCT
Like the UNION operator, using DISTINCT in our SELECT query directs SQL Server to filter out any duplicate rows that may be in the results, which it typically does by introducing a sort operation. If we already have an ORDER BY clause in the query, the sort may be necessary anyway so this would not be additional overhead, but if order is not important, and neither are duplicates, the DISTINCT clause is unnecessary and the query would likely be cheaper without it.
Rather than blindly applying a DISTINCT operator to our query, it's worth taking some time to investigate why there are duplicate rows in the results. It may be expected and intentional, but if we are getting duplicates in our results when they are not expected often ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access