Full answer
sql
WITH t(x) AS (VALUES (10), (10), (40))
SELECT AVG(x) AS avg_all, AVG(DISTINCT x) AS avg_distinct, SUM(DISTINCT x) AS sum_distinct FROM t;| avg_all | avg_distinct | sum_distinct |
|---|---|---|
| 20.0 | 25.0 | 50 |
The two 10s are separate rows, for example two orders of the same price. Removing one of them answers a different question ("average of distinct prices"), not "average order value".
SUM(DISTINCT x) is 50 for the same reason. These forms are occasionally useful, but they are a frequent wrong fix for double counting after joins, where the right fix is to aggregate before joining.
sql
WITH t(x) AS (VALUES (10), (10), (40))
SELECT AVG(x) AS avg_all, AVG(DISTINCT x) AS avg_distinct, SUM(DISTINCT x) AS sum_distinct FROM t;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- DISTINCT inside an aggregate removes duplicate values first
- AVG(DISTINCT) answers a different question than AVG
- Equal values can be different real events
- Fix join fan-out by aggregating earlier, not with DISTINCT
Common mistakes
- Using SUM(DISTINCT) to undo join duplication
- Assuming equal values are duplicates
Follow-ups
- When is COUNT(DISTINCT) the right choice?
- How do you fix double counting after a join?
Tips
- Ask whether equal values are separate events