A-Level Computer Science / Unit 8: Relational Databases and SQL

8.2.6 SQL DML: Aggregate Functions and GROUP BY

πŸ”’ Lesson slides are available to signed-in users. Sign in

8.2.6 SQL DML: Aggregate Functions and GROUP BY

COUNT, SUM and AVG calculate summaries. GROUP BY calculates a separate summary for each value group.

By the end of this page, you should be able to:

  • define and use the key terms accurately;
  • explain how the idea works using a new example;
  • apply the idea to a database design or SQL task.

1. Summarise a set of rows

An aggregate function turns several selected values into a summary. COUNT counts rows or non-NULL field values; SUM adds numeric values; AVG calculates a mean from numeric values.

2. Understand COUNT forms

COUNT(*) counts rows in the current result set or group, even when some other fields are NULL. COUNT(FieldName) counts only rows where that field has a value. WHERE can filter the rows before the aggregate is calculated.

3. GROUP BY creates separate groups

GROUP BY collects records that share a value in a chosen field. The aggregate is then calculated for each group. If a report needs one total for each delivery route, group by RouteID and calculate SUM(DeliveryFee).

4. Choose output fields carefully

A grouped query normally displays the grouping field and the aggregate result. Other fields may be ambiguous because each group can contain several values for them. Use WHERE to select the input rows before the grouping occurs.

Worked example

For Route(RouteID, DeliveryFee), SELECT RouteID, SUM(DeliveryFee) FROM Route GROUP BY RouteID; returns one total per route. Without GROUP BY, SUM(DeliveryFee) returns one total across the selected rows.

Common mistake to avoid

GROUP BY does not sort the result as its main purpose. It forms groups; use ORDER BY if a particular output order is required.

Interactive check

Choose an answer, read the explanation, and continue to the next example.

Try it

Check your understanding

Question 1 of 3
Score: 0 / 3

Independent practice

Try this original question before opening the suggested response.

In Review(ReviewID, ProductCode, Score), write a query that returns each ProductCode and its average Score. (3)

Suggested response
SELECT ProductCode, AVG(Score)
FROM Review
GROUP BY ProductCode;

Answering clearly

Use the technical term, state what it does, and connect your explanation to the details in the question.