Learn how to combine WHERE, GROUP BY, and aggregate functions like COUNT, SUM, and AVG into a single SQL query. This lesson teaches you the logical execution order SQL uses, how to filter rows before grouping them, and how to compute statistics across meaningful data subsets — with real examples and hands-on exercises.

Imagine you're a data analyst at a retail company and your manager walks over with a question: "Can you tell me the total revenue and average order value for each product category — but only for orders placed this year, and only for customers in the Northeast region?" That's not one question. That's three filtering conditions, two calculations, and a grouping all woven together into a single request. And yet, in SQL, the entire answer fits in one query.
This kind of question is the bread and butter of data work. Reports, dashboards, and business reviews all depend on being able to slice data into meaningful groups and then compute numbers within those slices. The good news is that SQL was built for exactly this — it has dedicated clauses for filtering rows before you count them, grouping the remaining rows into buckets, and then applying calculations to each bucket.
By the end of this lesson, you'll be able to write queries that combine filtering, grouping, and aggregation into clean, readable SQL. You won't just know the syntax — you'll understand why each clause belongs where it does and how they work together as a pipeline.
What you'll learn:
WHERE to filter individual rows before any grouping happensGROUP BY to organize rows into meaningful bucketsCOUNT, SUM, AVG, MIN, MAX) to each groupYou should have a basic familiarity with SQL SELECT statements and know how to filter rows with WHERE. If you're newer to SQL, work through SQL Basics: Master SELECT, FROM, WHERE Clauses and Build Your First Queries first. It also helps to have seen aggregate functions like COUNT() and SUM() before — if those are new to you, Grouping and Summarizing Data: COUNT, SUM, AVG, and GROUP BY for Beginners is a great warm-up.
Throughout this lesson we'll work with a fictional e-commerce company's orders database. Here are the two tables we'll query against:
-- orders table
-- order_id | customer_id | order_date | region | status | total_amount
-- ---------|-------------|-------------|-----------|-----------|-------------
-- 1001 | 42 | 2024-03-15 | Northeast | completed | 149.99
-- 1002 | 87 | 2024-01-08 | Southwest | completed | 220.00
-- 1003 | 42 | 2023-11-22 | Northeast | cancelled | 89.50
-- 1004 | 15 | 2024-05-01 | Northeast | completed | 310.75
-- ...
-- order_items table
-- item_id | order_id | product_category | quantity | unit_price
-- --------|----------|------------------|----------|----------
-- 5001 | 1001 | Electronics | 2 | 74.995
-- 5002 | 1001 | Accessories | 1 | 0.00
-- 5003 | 1002 | Home & Garden | 3 | 73.33
-- ...
Simple, realistic data. The kind you'd find at any company that sells things online.
Before we start combining clauses, we need to establish something that trips up almost every beginner: the order you write SQL clauses is not the order SQL executes them.
You write SQL like this:
SELECT ...
FROM ...
WHERE ...
GROUP BY ...
HAVING ...
ORDER BY ...
But SQL processes it in this order:
This matters enormously in practice. It means WHERE runs before GROUP BY, which means WHERE filters rows that haven't been grouped yet. And it means you can't reference a column alias you defined in SELECT inside a WHERE clause — the alias doesn't exist yet when WHERE runs.
Key insight
Think of SQL as a pipeline. Rows flow through each stage and get shaped, filtered, or grouped before reaching the next stage. Understanding this pipeline is the key to knowing where to put your conditions.
Let's start with just the WHERE clause. Suppose you want to look only at completed orders placed in 2024:
SELECT *
FROM orders
WHERE status = 'completed'
AND order_date >= '2024-01-01';
This gives you a filtered set of rows — only the rows that satisfy both conditions. Nothing is grouped or summarized yet. You're just narrowing the dataset down to the rows you care about.
This filtering step is powerful because it happens before grouping. When you later add a GROUP BY, the aggregation will only operate on these pre-filtered rows. That's the whole point: WHERE lets you define your universe of data before you start computing statistics.
Tip
When writing a new query, start with just SELECT * FROM table WHERE conditions and confirm you're seeing the right raw rows before you add any grouping. This saves a lot of debugging time.
For more on building precise filter conditions, see Advanced SQL Filtering and Sorting: Mastering WHERE, ORDER BY, and Query Optimization.
Once you've filtered your rows, GROUP BY organizes them into buckets. Think of it like sorting a stack of papers by color — every row that shares the same value in the grouping column gets put into the same pile.
Let's group those completed 2024 orders by region:
SELECT region
FROM orders
WHERE status = 'completed'
AND order_date >= '2024-01-01'
GROUP BY region;
The result of this query would be one row per region — each row represents one "bucket" of data. But we haven't actually calculated anything yet. The grouping just sets up the structure for what comes next.
Warning
Every column in your SELECT list must either appear in GROUP BY or be wrapped in an aggregate function. If you try to SELECT customer_id without grouping by it, SQL will throw an error (or in older MySQL, return unpredictable results). The rule is strict and exists for good reason — you can't display a single value for a column that has multiple different values within a group.
Now we layer in the actual calculations. Aggregate functions collapse multiple rows into a single value. The most common ones:
| Function | What it does |
|---|---|
COUNT(*) |
Counts rows in the group |
COUNT(column) |
Counts non-NULL values in that column |
SUM(column) |
Adds up all values |
AVG(column) |
Computes the arithmetic mean |
MIN(column) |
Returns the smallest value |
MAX(column) |
Returns the largest value |
Let's put them all together now. We want total revenue, average order value, and order count — by region — for completed orders in 2024:
SELECT
region,
COUNT(*) AS order_count,
SUM(total_amount) AS total_revenue,
AVG(total_amount) AS avg_order_value,
MIN(total_amount) AS smallest_order,
MAX(total_amount) AS largest_order
FROM orders
WHERE status = 'completed'
AND order_date >= '2024-01-01'
GROUP BY region;
This is a complete, working query that combines all three elements. The result might look like:
region | order_count | total_revenue | avg_order_value | smallest_order | largest_order
------------|-------------|---------------|-----------------|----------------|---------------
Northeast | 47 | 12,340.50 | 262.57 | 15.99 | 899.00
Southwest | 31 | 7,210.00 | 232.58 | 29.99 | 650.00
Southeast | 29 | 8,105.25 | 279.49 | 49.00 | 740.00
Each row represents a region. The aggregate functions ran independently within each region's bucket. The WHERE clause ensured that cancelled orders and orders from 2023 were never included in any bucket at all.
Key insight
The WHERE clause doesn't know anything about groups. It operates on individual rows. If you want to filter groups (for example, only show regions with more than 10 orders), that's what HAVING is for — but we'll cover that separately. For now, WHERE is your tool for row-level filtering.
A practical note: AVG() often returns a long decimal. In production queries, you'll almost always want to round it:
SELECT
region,
COUNT(*) AS order_count,
SUM(total_amount) AS total_revenue,
ROUND(AVG(total_amount), 2) AS avg_order_value
FROM orders
WHERE status = 'completed'
AND order_date >= '2024-01-01'
GROUP BY region;
ROUND(value, decimal_places) is available in all major SQL databases. It's a small thing that makes your output look professional and prevents downstream systems from choking on numbers like 262.5714285714.
You're not limited to grouping by a single column. You can group by any combination of columns, and SQL will create one bucket for each unique combination of values across all grouping columns.
Suppose you want to break down orders by both region and year:
SELECT
region,
EXTRACT(YEAR FROM order_date) AS order_year,
COUNT(*) AS order_count,
SUM(total_amount) AS total_revenue,
ROUND(AVG(total_amount), 2) AS avg_order_value
FROM orders
WHERE status = 'completed'
GROUP BY region, EXTRACT(YEAR FROM order_date)
ORDER BY order_year, region;
Notice a few things here:
order_date filter from WHERE so we can see multiple years.EXTRACT(YEAR FROM order_date) to both SELECT and GROUP BY — they must match.ORDER BY at the end sorts the output for readability.The result gives you one row per region-year combination. Twelve rows if you have three regions and four years of data.
Tip
You can use expressions — not just raw column names — inside GROUP BY. Date functions like EXTRACT(), DATE_TRUNC(), or YEAR() are especially useful for time-series breakdowns. See Master SQL String and Date Functions: Essential Data Transformation Skills for a full reference on date manipulation.
Real queries often involve more than one table. Let's say you want total quantity sold and average unit price — grouped by product category — but only for completed orders placed in 2024.
This requires joining orders to order_items:
SELECT
oi.product_category,
COUNT(DISTINCT o.order_id) AS order_count,
SUM(oi.quantity) AS total_units_sold,
ROUND(AVG(oi.unit_price), 2) AS avg_unit_price,
ROUND(SUM(oi.quantity * oi.unit_price), 2) AS total_revenue
FROM orders o
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.status = 'completed'
AND o.order_date >= '2024-01-01'
GROUP BY oi.product_category
ORDER BY total_revenue DESC;
Let's walk through what's happening here:
COUNT(DISTINCT o.order_id) counts unique orders (important when joining — without DISTINCT, you'd count one row per line item, inflating the count).Warning
When you join tables and then aggregate, watch out for row multiplication. If one order has 5 line items, that order's row gets duplicated 5 times in the joined result. SUM(total_amount) on the orders table would then count that order's total 5 times. Either aggregate from the detail table (as we did with quantity and unit_price), or use COUNT(DISTINCT order_id) to count orders correctly.
One of the most common beginner questions is: "If I want to only show categories with more than 100 units sold, do I put that in WHERE or somewhere else?"
The answer is HAVING. Here's why: WHERE runs before grouping — before SUM(oi.quantity) has even been calculated. You can't filter on a value that hasn't been computed yet.
HAVING runs after grouping, so it can reference aggregate results:
SELECT
oi.product_category,
SUM(oi.quantity) AS total_units_sold,
ROUND(AVG(oi.unit_price), 2) AS avg_unit_price
FROM orders o
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.status = 'completed'
AND o.order_date >= '2024-01-01'
GROUP BY oi.product_category
HAVING SUM(oi.quantity) > 100
ORDER BY total_units_sold DESC;
A simple mental rule: WHERE filters rows, HAVING filters groups. Put conditions on raw column values in WHERE. Put conditions on aggregated values in HAVING. For a deep dive into this distinction, see Ranking and Filtering Groups with HAVING: Writing Conditional Aggregates That Go Beyond WHERE.
Work through these progressively. Each builds on the previous.
Setup: Use the orders and order_items tables described above, or substitute any similar dataset you have available. Many free SQL sandboxes (SQLiteOnline, DB Fiddle, Mode Analytics) let you create and query tables with just a few clicks.
Exercise 1 — Warm-up: Row count by status
Write a query that counts how many orders exist for each status value (completed, cancelled, pending, etc.). No date filter yet. Just get a feel for the data distribution.
-- Your query here
SELECT status, COUNT(*) AS order_count
FROM orders
GROUP BY status;
Exercise 2 — Add a filter
Modify Exercise 1 to only include orders from 2024. How does the count change?
-- Your query here
SELECT status, COUNT(*) AS order_count
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY status;
Exercise 3 — Multiple aggregates
Write a query that shows, for each region, the number of completed orders in 2024, the total revenue, and the average order value (rounded to 2 decimal places). Order results by total revenue descending.
Exercise 4 — Multi-column grouping
Extend Exercise 3 to group by both region and month (use EXTRACT(MONTH FROM order_date) or your database's equivalent). This gives you a monthly breakdown per region.
Exercise 5 — Challenge: Join and aggregate
Write a query that joins orders to order_items and returns, for each product category, the total quantity sold and total revenue — but only for completed orders in 2024 from the Northeast region. Filter out any categories with fewer than 50 total units sold.
Mistake 1: Putting a non-aggregated column in SELECT that isn't in GROUP BY
-- Broken: customer_id isn't in GROUP BY
SELECT customer_id, region, COUNT(*)
FROM orders
GROUP BY region;
Fix: Either add customer_id to GROUP BY, or remove it from SELECT, or wrap it in an aggregate like COUNT(DISTINCT customer_id).
Mistake 2: Trying to filter on an aggregate in WHERE
-- Broken: SUM() can't go in WHERE
SELECT region, SUM(total_amount) AS revenue
FROM orders
WHERE SUM(total_amount) > 10000
GROUP BY region;
Fix: Move the aggregate condition to HAVING:
SELECT region, SUM(total_amount) AS revenue
FROM orders
GROUP BY region
HAVING SUM(total_amount) > 10000;
Mistake 3: Counting duplicates after a JOIN
-- May over-count if orders have multiple items
SELECT region, COUNT(*) AS order_count
FROM orders o
JOIN order_items oi ON o.order_id = oi.order_id
GROUP BY region;
Fix: Use COUNT(DISTINCT o.order_id) to count unique orders.
Mistake 4: Forgetting that NULL values are ignored by most aggregates
AVG(), SUM(), MIN(), MAX() all skip NULL values. COUNT(column) skips NULLs too — only COUNT(*) counts every row regardless. If your column has NULLs, your average might be computed on fewer rows than you expect. Use COALESCE(column, 0) inside the aggregate if you want NULLs treated as zero. For more on this, see NULL Handling in SQL: IS NULL, COALESCE, and NULLIF.
Mistake 5: Referencing a SELECT alias in WHERE
-- Broken: 'revenue' doesn't exist yet when WHERE runs
SELECT region, SUM(total_amount) AS revenue
FROM orders
WHERE revenue > 1000
GROUP BY region;
Fix: Use HAVING SUM(total_amount) > 1000 instead, or repeat the full expression in HAVING.
You've now seen the complete mechanics of combining WHERE, GROUP BY, and aggregate functions in a single SQL query. Let's recap the core pattern:
SELECT
grouping_column,
COUNT(*) AS count_alias,
SUM(column) AS sum_alias,
AVG(column) AS avg_alias
FROM table
WHERE row_level_conditions -- Filter rows BEFORE grouping
GROUP BY grouping_column -- Organize filtered rows into buckets
HAVING aggregate_conditions -- Filter groups AFTER aggregation
ORDER BY sort_expression; -- Sort the final output
The mental model to hold onto: SQL is a pipeline. WHERE narrows the rows that enter the grouping stage. GROUP BY organizes those rows into buckets. Aggregate functions compute statistics within each bucket. HAVING removes buckets that don't meet your criteria. SELECT assembles the final output.
Where to go next:
The queries you wrote in this lesson are genuinely useful. This isn't foundation-building for some distant future skill — this is the skill. Most of the reports and dashboards you'll ever build live in this territory: filtered subsets, grouped buckets, aggregate statistics, cleanly sorted results.
SQL Fundamentals