runtime
11 / 88

lesson 11 Calculations & data quality · intermediate

Group into summaries

Summarize rows that share the same group.

the idea

GROUP BY forms one group for each key. Aggregates then summarize each group. Select grouping columns and aggregates to avoid ambiguous output.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT category, COUNT(*) AS product_count
FROM products
GROUP BY category;

Watch for: Selecting an ungrouped name in SQLite can return an arbitrary member of the group.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Read product rows. Two products belong to each category. The input grain is one product.

    step-1.sql
    SELECT id,name,category
    FROM products;
  2. Count within groups. GROUP BY changes the grain to one category.

    step-2.sql
    SELECT category,COUNT(*) AS product_count
    FROM products
    GROUP BY category;

challenge 1

Show category and product_count for each product category.

Return categoryproduct_countany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.