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_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

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;
departmentheadcounttotal_salary
Accounting296000
Customer service238400
Management193600
Sales3158400
Warehouse275000

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_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-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;
statusorder_count
delivered11
open3
cancelled2
shipped2

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_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.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:

DatabaseUngrouped column in SELECTAlias after GROUP BY
MySQLError 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
PostgreSQLError, unless the column is functionally dependent, meaning you group by the primary key of its tableyes
SQL ServerError: "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 maximumyes

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.

Up next: HAVING

Only departments with at least two people, only categories that are running low: HAVING filters the groups that GROUP BY has built.

Practice HAVING

Write to us

Choose language

Select your preferred language