← Back to SQL, page 5

sql-0082 · Medium mid

What does SUM(DISTINCT amount) do, and why is it rarely the right fix for double counting?

SUM(DISTINCT x) adds each distinct value once, so two different rows with the same amount are counted only once. That is almost never what a business total means. It sometimes appears as a patch for join fan-out, where it hides the problem on some data and gives wrong totals on other data.

Full answer

DISTINCT inside an aggregate removes duplicate values before aggregating. For COUNT that is often useful. For SUM it usually is not.

sql
CREATE TABLE receipts (id INTEGER PRIMARY KEY, customer TEXT, amount INTEGER);
INSERT INTO receipts VALUES (1,'Ana',50),(2,'Ben',50),(3,'Chen',100);
sql
SELECT COUNT(*) AS receipts, SUM(amount) AS revenue, SUM(DISTINCT amount) AS sum_distinct FROM receipts;
receiptsrevenuesum_distinct
3200150

Ana and Ben each paid 50 and Chen paid 100. SUM(amount) is 200, the real revenue. SUM(DISTINCT amount) is 150, because the two 50s collapsed into one.

The pattern is common in queries that suffer from join fan-out. Someone notices doubled totals, adds DISTINCT, and the test data happens to have unique amounts, so the number looks right. Then real data with repeated amounts arrives and the total is quietly too low.

The real fix for fan-out is to aggregate each child table before joining. Use SUM(DISTINCT ...) only when the question really is about distinct values, for example "the sum of the distinct ticket prices offered", which is unusual.

sql
CREATE TABLE receipts (id INTEGER PRIMARY KEY, customer TEXT, amount INTEGER);
INSERT INTO receipts VALUES (1,'Ana',50),(2,'Ben',50),(3,'Chen',100);

SELECT COUNT(*) AS receipts, SUM(amount) AS revenue, SUM(DISTINCT amount) AS sum_distinct FROM receipts;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SUM(DISTINCT x) sums each distinct value once
  • Equal amounts from different rows are merged
  • It is not a fix for join duplication
  • COUNT(DISTINCT) is commonly useful; SUM(DISTINCT) rarely is

Common mistakes

  • Using SUM(DISTINCT) to hide fan-out from a join
  • Testing with data where every amount is unique

Follow-ups

  • How would you fix a total inflated by joining two child tables?
  • When is AVG(DISTINCT) meaningful?

Tips

  • Give a two-row example with equal amounts; it shows the flaw instantly