skipnothing/SQL
UNIT 04

Aggregation & Grouping

COUNT, SUM, GROUP BY, HAVING, collapsing many rows to one

Aggregation is how you turn a thousand orders into one revenue number, or one number per customer. GROUP BY is the rule for which rows collapse together; HAVING is WHERE for aggregates.

Loading…
BUILDS ON
TOPICS
#13

Aggregate Functions

Collapse a whole column to one number with COUNT, SUM, AVG, MIN and MAX, predict how each treats NULLs, and read several aggregates from one SELECT as a single summary row.

Six rows sit in the orders table, four carrying a real amount and two left blank. Ask for the total, the average, the largest, and the engine hands back a single row of numbers, the whole column folded into one.

12 min
#14

GROUP BY

Split rows into one group per distinct value, predict how grouping changes the result row count, and apply the rule that every selected column must be grouped or wrapped in an aggregate.

Six rows in orders, two from each of three buyers, and the whole-table total came back as one number: 188.50. Ask for the total per buyer instead, and three numbers come back, one each.

14 min
#15

HAVING vs WHERE

Filter rows with WHERE before grouping and whole groups with HAVING after, route each condition by what it reads, and know why an aggregate is rejected in WHERE but legal in HAVING.

Six orders rows, two of them refunded: drop the refunds and you have filtered rows. Keep only buyers whose remaining total tops 50, though, and the filter waits for a number that does not exist yet.

11 min
#16

COUNT(*) vs COUNT(col)

Pick between COUNT(*), COUNT(col), and COUNT(DISTINCT col), read the gap each leaves when the column holds NULLs or repeats, and ride the same skip-NULL rule to count only the rows that meet a condition.

Six rows sit in orders, two with no amount and one amount repeated. The question 'how many?' has three honest answers here, and which one you get depends on whether you're counting rows, values, or distinct values.

10 min
UNLOCKS
All units