Quiz
Warm-up from lesson 3-2: what does `SELECT DISTINCT genre FROM movies;` return?
From many rows to one number
Every query so far returned rows, but most business questions want a number: how many users signed up this week, what did the store earn today, what is the average order size. Nobody answers those by reading a million rows. Dashboards, reports, and analytics are built almost entirely from this lesson. Aggregate functions boil many rows down to a single value:
| Function | Answers |
|---|---|
COUNT(*) | how many rows? |
SUM(col) | what do the values add up to? |
AVG(col) | what is the average? |
MIN(col) / MAX(col) | smallest / largest value? |
This unit uses a cafe's orders table with columns customer, item, price. Averages often come out as long decimals like 5.83333333333333, so wrap them in ROUND(value, 2) to keep two decimal places.
Run the block: four questions, four one-row answers.
Code exercise · sql
Run it. Each SELECT prints one line: total orders, total revenue, cheapest and priciest item, and the rounded average price.
Aggregates respect WHERE
An aggregate runs after the row filter, so you can count or sum any slice of the table:
SELECT COUNT(*) FROM orders WHERE item = 'coffee';
First WHERE keeps only the coffee rows, then COUNT counts what is left. This one-two punch (filter, then aggregate) answers most everyday questions: revenue this month, users who never logged in, largest order over $10.
Code exercise · sql
Your turn. How much money has Ana spent in total? Write one SELECT that prints a single number.
COUNT(*) vs COUNT(column)
COUNT(*) counts rows. COUNT(price) counts rows whose price is not NULL, because aggregate functions skip NULLs (SUM and AVG skip them too). The two disagree exactly when your data has gaps, and that is often the point: COUNT(*) asks "how many orders?", COUNT(price) asks "how many orders have a price on record?".
The block below adds a free tap water with a NULL price, then runs both counts.
Code exercise · sql
Run it. Seven rows exist, but only six have a price, so COUNT(*) and COUNT(price) disagree by one.