SQL GROUP BY: summarize data by group
How many products are in each category? What does each department cost in salaries? Which product brings in the most revenue? GROUP BY gives you one row per group instead of one number for the whole table.
In short: SELECT category, COUNT(*) FROM products GROUP BY category; returns one row per category with its number of products. The rule that comes with it: every column in the SELECT list is either listed after GROUP BY or wrapped in a function like COUNT or SUM.
What you should know first: counting rows with COUNT, and totals and averages with SUM, AVG, MIN and MAX.
Try it now
You already know SELECT COUNT(*) FROM products: one number for the whole table. This time the same count should run separately for each category.
Task Purchasing wants to see how wide the product range is. Return one row per category with category and the number of products in that category.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
How GROUP BY works
Picture sorting all rows into piles, one pile for each value of the grouping column. Every aggregate function (COUNT, SUM, AVG, MIN, MAX) then works on each pile on its own, and each pile becomes exactly one row of the result. HR wants the headcount and salary total for each department:
SELECT department,
COUNT(*) AS headcount,
SUM(salary) AS total_salary
FROM employees
GROUP BY department;
| department | headcount | total_salary |
|---|---|---|
| Accounting | 2 | 96000 |
| Customer service | 2 | 38400 |
| Management | 1 | 93600 |
| Sales | 3 | 158400 |
| Warehouse | 2 | 75000 |
Ten employees turn into five rows. Customer service has two people but a total of only 38400: Laura Hughes has no salary on file yet, and SUM skips NULL. GROUP BY goes after FROM and WHERE and before ORDER BY, so the full order is SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT.
The key rule: grouped or aggregated
What should SELECT department, last_name, COUNT(*) FROM employees GROUP BY department show for Sales? Three people work there, but the row only has room for one last name. That's why every column in the SELECT list has to appear after GROUP BY or sit inside an aggregate function. MySQL, PostgreSQL and SQL Server refuse the query with an error. SQLite, the database behind these exercises, runs it and, according to its documentation, takes the last name from some row in the group. The result looks believable and is still pure chance.
Grouping by more than one column
You can list several columns after GROUP BY, separated by commas. Every combination that occurs in the data then forms its own group, so GROUP BY country, segment keeps business customers in the UK apart from business customers in the USA. The order of the columns after GROUP BY doesn't change the groups, only how easy the query is to read.
Task Marketing is planning campaigns by country and customer type. Return country, segment and the number of customers for every combination of country and segment that exists.
customers 12 rows, 7 columns
| customer_id | name | city | country | customer_since | segment | phone |
|---|---|---|---|---|---|---|
| 1 | Harbor Fremont Partners | Boston | USA | 2021-03-15 | Business | 617-555-0142 |
| 2 | Emily Carter | Chicago | USA | 2022-07-01 | Consumer | NULL |
| 3 | Riverside County Office | Riverside | USA | 2020-11-20 | Government | 951-555-0110 |
| 4 | Raj Patel | Leeds | UK | 2023-01-09 | Consumer | 0113 496 0123 |
| 5 | Lakeview Hotel Ltd | Manchester | UK | 2022-04-18 | Business | 0161 496 0456 |
| 6 | Olivia Brooks | Austin | USA | 2024-02-27 | Consumer | NULL |
| 7 | Greene & Shaw LLP | London | UK | 2021-09-05 | Business | 020 7946 0321 |
| 8 | Maple Grove High School | Austin | USA | 2023-08-14 | School | 512-555-0187 |
| 9 | Chloe Evans | Boston | USA | 2025-05-30 | Consumer | 617-555-0199 |
| 10 | Northline Printing Co | Toronto | Canada | 2020-06-12 | Business | 416-555-0133 |
| 11 | Daniel Kim | Seattle | USA | 2024-10-03 | Consumer | NULL |
| 12 | Westbrook Dental Clinic | Chicago | USA | 2022-12-01 | Business | 312-555-0164 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Sorting by the result
With grouped results you usually want to sort by the number you just calculated. ORDER BY accepts the aggregate function itself or its alias. How many orders are there per status, most common first?
SELECT status, COUNT(*) AS order_count
FROM orders
GROUP BY status
ORDER BY order_count DESC, status;
| status | order_count |
|---|---|
| delivered | 11 |
| open | 3 |
| cancelled | 2 |
| shipped | 2 |
cancelled and shipped are tied at 2, so the second sort column, status, keeps their order fixed. The ORDER BY lesson covers this in detail. Add LIMIT and you have a top list:
Task Management wants the five products with the highest revenue. From the order lines, return product_id, the units ordered (sum of quantity) and the revenue (sum of quantity times unit price), highest revenue first, top five only. Count every order line.
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
GROUP BY and Excel PivotTables
If you build PivotTables in Excel, you already know the idea. The column after GROUP BY is the field in the Rows area, and COUNT or SUM is the field in the Values area set to Count or Sum. Two columns after GROUP BY are like two fields stacked in Rows. Two differences: GROUP BY gives you no grand total row, and there's nothing to refresh, because the query recalculates on the current data every time it runs.
Common mistakes
Forgetting GROUP BY
SELECT category, COUNT(*) FROM products counts the whole table and returns a single row with 12 next to some category. The exercise tells you "Your query returns only 1 row. Wanted: 6 rows." As soon as an aggregate is involved and you want one row per group, you need GROUP BY.
Grouping by only some of the columns
SELECT country, segment, COUNT(*) FROM customers GROUP BY country runs without an error in SQLite, but returns 3 rows instead of 7, with a random value in the segment column. The exercise points out the wrong row count. Every column that isn't inside COUNT or SUM belongs after GROUP BY as well.
GROUP BY in the wrong place
... ORDER BY revenue DESC LIMIT 5 GROUP BY product_id gives a syntax error near "GROUP", along with a reminder of the order SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
Summing first, multiplying second
SUM(quantity) * SUM(unit_price) multiplies the total quantity by the sum of all prices, which isn't revenue at all. The right version is SUM(quantity * unit_price): calculate each line first, then add up. The exercise says the columns and row count match but the values don't.
GROUP BY in MySQL, PostgreSQL, SQL Server and SQLite
GROUP BY with column names and aggregate functions works the same everywhere. The differences show up with columns that are neither grouped nor aggregated, and with aliases after GROUP BY:
| Database | Ungrouped column in SELECT | Alias after GROUP BY |
|---|---|---|
| MySQL | Error while ONLY_FULL_GROUP_BY is on (the default). Allowed when the column is functionally dependent on the grouping, for example when you group by the primary key. Workaround: ANY_VALUE(column) | yes |
| PostgreSQL | Error, unless the column is functionally dependent, meaning you group by the primary key of its table | yes |
| SQL Server | Error: "Column … is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" | no |
| SQLite (these exercises) | Allowed (a "bare column"), value from an arbitrary row of the group; with exactly one MIN or MAX, from the row holding that minimum or maximum | yes |
Write your queries so they run anywhere: every column grouped or aggregated, and the column itself after GROUP BY rather than an alias.
Sources: MySQL Reference Manual (MySQL Handling of GROUP BY), PostgreSQL documentation (SELECT), Microsoft Learn (SELECT - GROUP BY), sqlite.org (SELECT, section Bare columns in an aggregate query).
FAQ
Does GROUP BY sort the result?
Don't count on it. The MySQL manual states plainly that GROUP BY no longer sorts implicitly in current versions. If the order matters, add ORDER BY.
What's the difference between GROUP BY and DISTINCT?
SELECT DISTINCT category FROM products and SELECT category FROM products GROUP BY category return the same six rows. Only GROUP BY lets you count or sum per category, though. DISTINCT just removes duplicate rows.
What happens to NULL in the grouping column?
All rows with NULL end up in one shared group, as the SQLite documentation describes. Group the employees by manager_id and Karen Mitchell, who has no manager, gets her own row with NULL.
Can I group by a calculation, such as the month?
Yes. SELECT substr(order_date, 1, 7) AS month, COUNT(*) FROM orders GROUP BY substr(order_date, 1, 7) counts orders per month, with 5 in June. Dates get their own lesson later in this level.