01 / 21
SUM

Aggregates with
WHERE Filters

Learn how to combine aggregate functions like COUNT, SUM, and AVG with WHERE clauses to compute summaries on filtered subsets of your data.

SQL

What Are Aggregate Functions?

Aggregate functions take many rows of data and collapse them into a single summary value. Think of them as calculators that operate on entire columns at once.

COUNT
Counts how many rows exist
SUM
Adds up all values in a column
AVG
Calculates the mean of a column
MAX / MIN
Finds the largest or smallest value

What Does WHERE Do?

The WHERE clause is a row-level filter. Before any aggregation happens, WHERE examines each row individually and keeps only those that match the condition.

All Rows Alice, 92 Bob, 55 Clara, 88 Dan, 42 Eve, 95 Frank, 61 WHERE
\( \text{score} > 70 \)
Filtered Alice, 92 Clara, 88 Eve, 95 3 rows remain

Why Combine Aggregates with WHERE?

Real questions are rarely about all the data. You almost always need summaries of a specific subset: sales from last month, students who passed, orders above a certain amount.

1
Targeted insights: "What is the average score of students who passed?"
2
Data quality: Exclude invalid or irrelevant rows before computing totals.
3
Business logic: "How many orders shipped to California cost more than \(\$100\)?"

The Core Pattern

SELECT aggregate_function(column) FROM table_name WHERE condition;

The WHERE clause never sees the aggregate result: it runs before the aggregate is calculated. This is the single most important concept in this lesson.

SQL Execution Order

Step 1 FROM Step 2 WHERE Step 3 SELECT + AGG Load all rows from the table Keep only rows matching condition Run aggregate on filtered rows Example: "Average score of passing students"
SELECT AVG(score) FROM students WHERE \( \text{score} \ge 70 \);
WHERE removes failing students → AVG runs on passers only

WHERE vs HAVING

Students often confuse WHERE and HAVING. They both filter, but they operate at different stages of query processing.

WHERE HAVING
Filters Individual rows Groups (after GROUP BY)
Runs Before aggregation After aggregation
Can reference Column values Aggregate results
Example WHERE price \(>\) 10 HAVING SUM(price) \(>\) 100

How to Build the Query

1
Identify the table: Which table holds the data you need?
2
Define the filter: What condition must each row satisfy? Write the WHERE clause.
3
Choose the aggregate: Do you need COUNT, SUM, AVG, MAX, or MIN?
4
Pick the column: Which column does the aggregate operate on?
5
Assemble: SELECT aggregate(column) FROM table WHERE condition;

Example 1: COUNT with WHERE

Question: How many students scored above 80 on the exam?

namescore
Alice92
Bob55
Clara88
Dan42
Eve95
Frank61
SELECT COUNT(*) AS high_scorers FROM students WHERE score > 80;

Example 2: SUM with WHERE

Question: What is the total revenue from orders placed in January 2024?

SELECT SUM(amount) AS jan_revenue FROM orders WHERE order_date >= '2024-01-01' AND order_date < '2024-02-01';

Example 3: AVG with Multiple Conditions

Question: What is the average price of electronics that are currently in stock?

SELECT AVG(price) AS avg_electronics_price FROM products WHERE category = 'Electronics' AND stock_qty > 0;

Watch Out for NULL Values

Aggregate functions handle NULLs in specific ways, and WHERE interacts with NULLs too. Understanding this prevents subtle bugs.

Aggregates + NULL
COUNT(*) counts all rows. COUNT(column) skips NULLs. SUM, AVG, MAX, MIN all ignore NULL values.
WHERE + NULL
WHERE column = value never matches NULL. Use WHERE column IS NULL or IS NOT NULL explicitly.
-- Count students with a known score SELECT COUNT(score) FROM students; -- Count ALL students including those with NULL scores SELECT COUNT(*) FROM students;

Adding GROUP BY to the Mix

When you use GROUP BY alongside WHERE, the execution order is: FROM → WHERE → GROUP BY → HAVING → SELECT.

SELECT department, AVG(salary) AS avg_salary FROM employees WHERE hire_date >= '2020-01-01' GROUP BY department;

The Full Query Pipeline

FROM WHERE GROUP BY HAVING SELECT + AGG WHERE filters individual rows (before grouping) HAVING filters groups (after aggregation) SELECT computes final aggregate values Key: You cannot use an aggregate inside WHERE

Common Mistakes

✕ Aggregate in WHERE
Writing \(\text{WHERE AVG(score)} > 80\) causes an error. WHERE runs before aggregation, so aggregate results do not exist yet. Use HAVING instead.
✕ Confusing COUNT(*) and COUNT(col)
COUNT(*) counts all rows including NULLs. COUNT(email) skips rows where email is NULL. Pick the right one for your question.
✕ Forgetting NULL comparisons
WHERE status \(=\) NULL returns zero rows. NULL is not equal to anything: use WHERE status IS NULL instead.

Quick Reference Table

Pattern SQL Template When to Use
Simple aggregate SELECT AGG(col) FROM t Summary of all rows
Aggregate + WHERE SELECT AGG(col) FROM t WHERE ... Summary of filtered rows
Grouped aggregate ... GROUP BY col Summary per category
Grouped + WHERE ... WHERE ... GROUP BY col Filter rows, then group
Grouped + HAVING ... GROUP BY col HAVING AGG(...) ... Filter groups by aggregate

Question 1 of 5

You want to find the total sales amount for orders placed in 2024. Which query is correct?

Question 2 of 5

Why does \(\text{WHERE AVG(score)} \gt 80\) cause an error?

Question 3 of 5

Given a products table, which query counts only in-stock items in the "Books" category?

Question 4 of 5

What is the correct execution order when a SQL query contains FROM, WHERE, GROUP BY, and SELECT?

Question 5 of 5

A table has 100 rows. 20 rows have a NULL value in the email column. What does SELECT COUNT(email) FROM users; return?