Basic Aggregate
Functions in SQL
Learn to summarize entire columns of data with five powerful functions: COUNT, SUM, AVG, MIN, and MAX.
What Are Aggregate Functions?
An aggregate function takes a whole column of values and collapses them into a single result. Instead of seeing every individual row, you get one summary number: a total, an average, a count, or an extreme value.
Why Aggregate Functions Matter
Real databases can contain millions of rows. You rarely want to read every single row: you want answers. Aggregate functions let you ask big-picture questions directly in SQL.
Meet the Five Functions
The General Syntax
FROM table_name
WHERE condition; -- optional filter
COUNT: Counting Rows
SELECT COUNT(*) FROM students;
-- Count only non-NULL emails
SELECT COUNT(email) FROM students;
SUM and AVG: Totals and Means
SELECT SUM(score) FROM exams;
-- Average score
SELECT AVG(score) FROM exams;
MIN and MAX: Extremes
SELECT MIN(price) FROM products;
-- Most recent order date
SELECT MAX(order_date) FROM orders;
Key Distinction: COUNT(*) vs COUNT(column)
| id | name | |
|---|---|---|
| 1 | Alice | alice@mail.com |
| 2 | Bob | NULL |
| 3 | Carol | carol@mail.com |
| 4 | Dave | NULL |
| 5 | Eve | eve@mail.com |
How to Apply: Step by Step
Example 1: Simple COUNT
Question: How many orders were placed in the orders table?
FROM orders;
| total_orders |
|---|
| 847 |
Example 2: SUM with a Filter
Question: What is the total revenue from orders placed in January 2024?
FROM orders
WHERE order_date >= '2024-01-01'
AND order_date < '2024-02-01';
| jan_revenue |
|---|
| 42,350.00 |
Example 3: Multiple Aggregates at Once
Question: Show the count, average, min, and max score from the exams table.
COUNT(score) AS num_scores,
AVG(score) AS avg_score,
MIN(score) AS lowest,
MAX(score) AS highest
FROM exams;
| num_scores | avg_score | lowest | highest |
|---|---|---|---|
| 120 | 73.5 | 28 | 100 |
Common Mistakes to Avoid
Summary Comparison
| Function | Returns | Works On | Ignores NULL? |
|---|---|---|---|
| COUNT(*) | Row count | Any | No |
| COUNT(col) | Non-NULL count | Any | Yes |
| SUM | Total | Numeric | Yes |
| AVG | Mean | Numeric | Yes |
| MIN | Smallest | Any orderable | Yes |
| MAX | Largest | Any orderable | Yes |
Question 1 of 5
Which SQL function would you use to find the total sales amount across all rows in a sales table?
Question 2 of 5
A table has 10 rows. The email column is NULL in 3 of those rows. What does COUNT(email) return?
Question 3 of 5
Which query correctly finds the highest price in a products table?
Question 4 of 5
A scores column contains: 80, NULL, 90, 70, NULL. What does AVG(score) return?
Question 5 of 5
What is wrong with this query?
SELECT name, COUNT(*) FROM students;