Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
SQL

Writing SQL to Calculate Totals, Averages, and Counts Across Filtered Subsets: Combining WHERE, GROUP BY, and Aggregate Functions in One Query

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.

🌱 Foundation15 min readNov 29, 2026Updated Nov 29, 2026
Writing SQL to Calculate Totals, Averages, and Counts Across Filtered Subsets: Combining WHERE, GROUP BY, and Aggregate Functions in One Query
On this page
  • Prerequisites
  • The Dataset We'll Use
  • How SQL Actually Executes a Query (The Logical Order)
  • Step 1: Filtering Rows with WHERE Before Grouping
  • Step 2: Grouping Rows with GROUP BY
  • Step 3: Applying Aggregate Functions to Each Group
  • Rounding Your Results
  • Grouping on Multiple Columns
  • A More Complex Example: Filtering and Grouping Across Two Tables
  • The WHERE vs. HAVING Distinction
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps

Writing SQL to Calculate Totals, Averages, and Counts Across Filtered Subsets: Combining WHERE, GROUP BY, and Aggregate Functions in One Query

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:

  • How SQL processes a query in a specific logical order that determines what goes where
  • How to use WHERE to filter individual rows before any grouping happens
  • How to use GROUP BY to organize rows into meaningful buckets
  • How to apply aggregate functions (COUNT, SUM, AVG, MIN, MAX) to each group
  • How to combine all three in a single, correct query that answers real business questions

Prerequisites

You 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.


The Dataset We'll Use

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.


How SQL Actually Executes a Query (The Logical Order)

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:

  1. FROM — identify the table(s)
  2. WHERE — filter individual rows
  3. GROUP BY — organize the surviving rows into groups
  4. HAVING — filter the groups themselves
  5. SELECT — compute and return the final columns
  6. ORDER BY — sort the result

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.


Step 1: Filtering Rows with WHERE Before Grouping

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.


Step 2: Grouping Rows with GROUP BY

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.


Step 3: Applying Aggregate Functions to Each 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.


Rounding Your Results

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.


Grouping on Multiple Columns

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:

  1. We removed the order_date filter from WHERE so we can see multiple years.
  2. We added EXTRACT(YEAR FROM order_date) to both SELECT and GROUP BY — they must match.
  3. 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.


A More Complex Example: Filtering and Grouping Across Two Tables

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:

  • FROM + JOIN: We're pulling from both tables. For a refresher on how joins work, see SQL JOINs Explained with Real-World Examples.
  • WHERE: Filters rows where the order is completed and in 2024 — operating on the joined result, before any grouping.
  • GROUP BY: Creates one bucket per product category.
  • SELECT with aggregates: Each function runs within its category bucket. COUNT(DISTINCT o.order_id) counts unique orders (important when joining — without DISTINCT, you'd count one row per line item, inflating the count).
  • ORDER BY total_revenue DESC: Sorts the results so the highest-revenue categories appear first.

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.


The WHERE vs. HAVING Distinction

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.


Hands-On Exercise

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.


Common Mistakes & Troubleshooting

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.


Summary & Next Steps

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:

  • Ready to filter groups more precisely? Filtering Groups After Aggregation: Writing HAVING Clauses That Answer Real Business Questions goes deeper on HAVING.
  • Want to add conditional logic inside your aggregates — like summing only certain rows within a group? Combining Aggregates with Conditional Logic: GROUP BY, HAVING, and CASE WHEN in Practice is your next stop.
  • Ready to tackle multi-table reporting? Multi-Table Reporting with JOIN and GROUP BY: Aggregating Across Relationships in a Single Query will push your skills to the next level.

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.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

SQL Fundamentals

Previous

Writing SQL to Identify and Exclude Outliers Using Subqueries and Aggregate Thresholds

Related Insights

SQLPractitioner

Writing SQL to Compare Rows Within a Partition Using LEAD and LAG: Calculating Deltas, Detecting Changes, and Handling Boundary Conditions

20 min
SQLExpert

Writing SQL to Identify and Exclude Outliers Using Subqueries and Aggregate Thresholds

28 min
SQLFoundation

Understanding OVER(): How Window Functions See Your Data Before Aggregation

16 min

On this page

  • Prerequisites
  • The Dataset We'll Use
  • How SQL Actually Executes a Query (The Logical Order)
  • Step 1: Filtering Rows with WHERE Before Grouping
  • Step 2: Grouping Rows with GROUP BY
  • Step 3: Applying Aggregate Functions to Each Group
  • Rounding Your Results
  • Grouping on Multiple Columns
  • A More Complex Example: Filtering and Grouping Across Two Tables
  • The WHERE vs. HAVING Distinction
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps