DF040: The DISTINCT keyword is used in the aggregate function.

Last modified: December 25, 2024

The topic describes the DF040 T-SQL code analysis rule.

Category

BEST PRACTICE

Message

The DISTINCT keyword is used in the aggregate function.

Description

Using DISTINCT in aggregate functions can cause significant performance degradation.

Additional information

It should be noted that using DISTINCT in aggregate functions can lead to performance degradation, especially when dealing with large datasets. This may happen because DISTINCT requires the database engine to sort and eliminate duplicate values before performing the aggregation, which can be resource-intensive and time-consuming.

Noncompliant code example

SELECT COUNT(DISTINCT id) AS count_id FROM dbo.DemoTable
GO

Compliant solution

SELECT COUNT(id) AS count_id FROM dbo.DemoTable
GO