Chapter 8 · Lesson 3 of 8
WHERE Filters Before GROUP BY
Learn why WHERE removes individual rows before GROUP BY runs, and total only the larger sales per region in a hands-on query.
WHERE removes individual rows before any grouping or aggregation happens.
If you write:
SELECT region, SUM(amount) AS total_amount
FROM sales
WHERE amount >= 900
GROUP BY regiononly sales with amount >= 900 participate in the grouped totals. Smaller rows are gone before GROUP BY ever runs.
This is why WHERE is for row-level filters, not group-level filters.
Sample data
This lesson loads the sales table (8 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for sales
CREATE OR REPLACE TABLE sales (
id INTEGER,
salesperson VARCHAR,
region VARCHAR,
amount DECIMAL(10,2),
quantity INTEGER,
sale_date DATE
);
INSERT INTO sales VALUES
(1, 'Alice', 'West', 1200, 3, '2024-01-05'),
(2, 'Bob', 'East', 850, 2, '2024-01-08'),
(3, 'Alice', 'West', 640, 1, '2024-01-11'),
(4, 'Diana', 'South', 430, 5, '2024-01-12'),
(5, 'Eve', 'West', 1500, 4, '2024-02-01'),
(6, 'Frank', 'East', 920, 2, '2024-02-03'),
(7, 'Grace', 'North', 760, 2, '2024-02-07'),
(8, 'Bob', 'East', 1100, 3, '2024-02-10');Practice challenge
Only consider sales with amount >= 900. Then return region and total_amount, ordered by region.
Hint: Use WHERE amount >= 900 before GROUP BY region.
Run your query in the editor and the lesson checks the result automatically.
Lessons in Execution Order
Understand the logical order in which SQL evaluates FROM, WHERE, GROUP BY, HAVING, window functions, SELECT, ORDER BY, and LIMIT.