Lesson 7 of 13 · 16 min
Distinct aggregates
By the end of this lesson you can count distinct customers, orders or products per group, compute per-customer ratios from them, and explain why SUM(DISTINCT) and adding up distinct counts give wrong answers.
You met COUNT(DISTINCT column) in the first lesson of this track. Combined with GROUP BY it becomes one of the most useful tools in reporting: inside each group, PostgreSQL collects the column's values, removes duplicates and NULLs, and counts what is left.
It matters whenever the rows of a table are events (orders, order lines, payments, returns) but the question is about things that can appear in many events (customers, products, orders).
This lesson, its 5 graded exercises and every other Members lesson in SQL Quest come with a Formula Quest membership that includes SQL (Single Quest with SQL selected, Quest Trio including SQL, or Quest Unlimited), or with SQL access from your organization.
Free to everyone: all of SQL Foundations and Retrieving and Filtering Data, the first lesson of every track, the playground, the dataset library and the SQL reference. See free lessons