← Back to SQL, page 16

sql-0307 · Medium mid

What does AVG(DISTINCT x) return for the values 10, 10 and 40?

25.0. DISTINCT removes the duplicate 10 before averaging, so the average is over 10 and 40. Plain AVG would give 20.0. DISTINCT inside an aggregate changes the statistic, so use it only when duplicates are truly meaningless.

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_allavg_distinctsum_distinct
20.025.050

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