Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

AC 2.1: Grouping rows and counting each group

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

55 minutes

A count for every kind

Counting all the sales gives one number. The manager wants more: how many items does each category hold?

Asking once per category would be slow. One grouped question answers all of them.

Key words

WordWhat it means
Databasean organised store of tables that you can ask questions
SQLthe language used to ask a database for data
Queryone question written in SQL
GROUP BYputs rows with the same value in a column into one group
Groupall the rows that share one value, such as every drink
COUNTgives how many rows there are in each group
Summary rowone row in the answer that stands for a whole group

The cells students fill in are left blank in this preview.

By the end of this lesson

Note

I can use GROUP BY with COUNT to count the rows in each group, and put the clauses in the right order.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

How GROUP BY works

Imagine sorting the products into piles, one pile for each category. GROUP BY category does that. Each pile becomes one row in the answer.

COUNT(*) then counts the rows inside each pile.

Try it: count each category

Code: sql
SELECT category, COUNT(*) AS items
FROM products
GROUP BY category;

-- How many sales did each payment type have?
SELECT paid_by, COUNT(*) AS sales
FROM sales
GROUP BY paid_by;

Worked example: piles of products

categoryRows in the pileCOUNT(*)
drinkCola, Orange juice, Water3
fruitApple, Banana2
lunchCheese roll, Chicken wrap, Cheese toastie3
snackCrisps, Cookie2

The cells students fill in are left blank in this preview.

The order of the clauses

A query with every clause has a fixed order. WHERE comes before GROUP BY, because rows are filtered first and then grouped. ORDER BY comes last.

Order: SELECT, FROM, WHERE, GROUP BY, ORDER BY.

Check the order

Have a go

Check the order

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

The lesson goes on

7 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.