Syllabus Lesson 69 of 239 · SQL & Databases
SQL & Databases

Aggregates & GROUP BY

Databases summarise. Aggregate functions collapse many rows into one number: COUNT(*), SUM(col), AVG(col), MIN, MAX. On their own they summarise the whole table:

SELECT COUNT(*), AVG(price) FROM products;

GROUP BY runs the aggregate per group instead: one row out per distinct value of the grouping column.

SELECT category, SUM(stock) FROM products GROUP BY category;
-- one (category, total) row per category

Write stock_by_category(con) returning a dict {category: total_stock} built from SELECT category, SUM(stock) ... GROUP BY category. Press Run.

Your turn

Write stock_by_category(con) that returns a dict mapping each category to the SUM of its stock, using SELECT category, SUM(stock) FROM products GROUP BY category. Build the dict from the returned (category, total) rows.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output