Aggregate functions
SQL · 15 questions
Short notes
Key idea
Aggregate functions squeeze many rows into one value: how many, how much, the average, the smallest, the largest.
Syntax
SELECT COUNT(*) AS orders,
COUNT(coupon_code) AS with_coupon,
COUNT(DISTINCT customer_id) AS customers,
SUM(amount), AVG(amount), MIN(amount), MAX(amount)
FROM orders;
Example
Average order value in March:
SELECT ROUND(AVG(amount), 2) AS avg_order
FROM orders
WHERE order_date >= '2024-03-01' AND order_date < '2024-04-01';
WHERE filters first, then the average is taken over the rows left.
Traps
COUNT(*)counts rows;COUNT(col)skips NULLs in that column.AVGignores NULLs, so it's the average of the known values, not of all rows.- Integer division: PostgreSQL and SQL Server give
5 / 2 = 2; DuckDB and MySQL give 2.5. Write* 1.0so a percentage is right everywhere. - Don't mix plain columns with aggregates without
GROUP BY;SELECT city, COUNT(*) FROM tis an error.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
What does
COUNT(city)count? - Question 2medium
The
customerstable has 40 rows, and 3 customers have no city. What does this return?SELECT COUNT(*) - COUNT(city) FROM customers;
- Question 3hard
order_itemshas 166 lines. 27 of them have no discount recorded. How many rows doesCOUNTsee here?SELECT COUNT(quantity * unit_price - discount) FROM order_items;
- Question 4medium
A column has the values 10, 20, and NULL. What is
AVG(column)? - Question 5medium
No order has the status
'lost'. What does this query return?SELECT SUM(amount) FROM orders WHERE status = 'lost';
Aggregate functions
Aggregate functions
Aggregate functions
Aggregate functions
Aggregate functions
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.