DSA Factory
Free SQL queries lessonsSQL queries · Stage 2 · Counting and grouping · Step 1

Summarise with COUNT, SUM and AVG

Turn many rows into one with aggregate functions, and know what NULL does to them. About 9 minutes.

Many rows in, one row out

"How many books are there?" "What's the average mark?" These questions don't want a list. They want one number about the whole table.

An aggregate function reads all the rows and gives back one value: COUNT for how many, SUM for the total, AVG for the average, MIN and MAX for the smallest and largest. WHERE runs first, so you can aggregate just the rows that pass.

Aggregates: collapse many rows into one answer.
In code
SELECT COUNT(*) AS papers,
       SUM(score) AS total,
       MAX(score) AS best
FROM marks
WHERE subject = 'Maths';

What NULL and empty tables do

COUNT(*) counts rows, whatever they hold. COUNT(score) counts only the rows where score is not NULL, and SUM, AVG, MIN and MAX skip NULLs too. AVG divides by the values it saw, not the number of rows.

On an empty set, COUNT gives 0 but SUM, AVG, MIN and MAX give NULL, because there is nothing to add up.

COUNT(*) vs COUNT(col): rows, or values that exist.
How many rows, how many scores, what average
exams
studentscore
Asha80
RaviNULL
Meera60
Kabir100

COUNT(*) counts every row: 4.

Move 1 of 3
Quick check

A table has 5 rows, and cgpa is NULL in two of them. What does COUNT(cgpa) return?

  1. A3
  2. B5
  3. C2
Show the answer

3. COUNT(column) counts only the rows where the column is not NULL.

Your problem

Class summary

The marks table has one row per paper, and a score that is NULL until it is marked. Show, in one row, the number of papers as papers, the average of the marked scores as average, and the highest score as best.

Tables
marks(id, student, score)

Up to 2,000 papers

Write the query in your browserFree account, no card. Your query runs on real tables, with hints if you get stuck, and your progress is saved.
Sign up free to solve