Chapter 4 · Lesson 2 of 3
Summarizing with GROUP BY
Summarize rows per category with GROUP BY and SUM, and learn the rule that every selected column must be grouped or aggregated.
GROUP BY collects rows into groups before applying aggregate functions.
For example, to total sales by region:
SELECT region, SUM(amount) AS total_amount
FROM sales
GROUP BY regionNow SUM(amount) runs once per region instead of once for the whole table.
Remember this rule: when you use GROUP BY, every selected column must either be grouped or aggregated.
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
Show total sales by region. Return region and total_amount, ordered by total_amount descending.
Hint: SELECT region, SUM(amount) AS total_amount FROM sales GROUP BY region ORDER BY total_amount DESC
Run your query in the editor and the lesson checks the result automatically.
Lessons in DISTINCT and GROUP BY
Remove duplicates with DISTINCT, summarize per category with GROUP BY, and filter grouped results with HAVING.
Related guides
SQL DISTINCT, GROUP BY, and HAVING: From Unique Values to Grouped Reports
DISTINCT cleans up repeated values, GROUP BY creates summaries per category, and HAVING filters those summaries after aggregation.
How to Analyze a CSV File with SQL: A Step-by-Step Walkthrough
From raw CSV export to answer: confirm the detected column types, filter and aggregate with SQL, join a lookup file, and export only the result you need.
Parquet vs CSV for SQL Analysis: Types, Columnar Reads, and Memory Limits
Parquet stores typed columns that engines can read selectively. See what that means for SQL analysis and where browser memory still sets the limit.