runtime
10 / 88

lesson 10 Calculations & data quality · intermediate

COUNT, SUM & AVG

Count rows and calculate totals and averages.

the idea

Aggregate functions collapse rows into a summary. COUNT(*) counts rows; COUNT(column) excludes NULL. SUM adds numeric values; AVG finds their mean.

tables in this lesson

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

customers4 columns · 8 rows
idinteger · keynametextcitytextjoined_attext
1AliceChicago2024-01-10
2BenAustin2024-02-12
3CaraSeattle2024-03-05
4DevChicago2024-04-20
5ElenaNULL2024-05-01

showing 5 of 8 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 COUNT(*) AS customer_count
FROM customers;

Watch for: COUNT(city) excludes Elena because her city is NULL.

build it step by step

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

  1. Look at the rows being counted. Each customer is one row. An aggregate without GROUP BY collapses the whole table into one summary.

    step-1.sql
    SELECT id, name
    FROM customers;
  2. Collapse to a single count. COUNT(*) counts rows. SUM and AVG work the same way: many input rows become one summary value.

    step-2.sql
    SELECT COUNT(*) AS customer_count
    FROM customers;

challenge 1

Return the number of customers as customer_count.

Return customer_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.