GROUP BY
rows into buckets, one answer per bucket. why every selected column must be grouped or aggregated.
- address
- everything.basics.group_by
- part
- part 2, one table
- chapter
- chapter 11 of 12
- reading time
- 9 min
GROUP BY sorts rows into buckets, one bucket per different value of the key, and hands on one row per bucket. so every column SELECT asks for has to be grouped (the bucket's label, one value by definition) or aggregated (many values folded into one).
that's the rule behind the most common error in SQL. it isn't bureaucracy, it's arithmetic.
the picture
you know this one: column "courses.title" must appear in the GROUP BY clause or be used in an aggregate function. it reads like a form you filled in wrong. it's actually a very reasonable complaint, and it makes sense the moment you see what GROUP BY does to a table.
think of a mail room. every letter (a row) goes into a pigeonhole by its department (the key). when the sorting's done, you write one card per pigeonhole: the label on the hole, how many letters are in it, how many pages they add up to. what you can't write on the card is "the sender": the CS hole has five letters from five senders, and the card has one line.
- 1SELECT dept, count(*) AS courses, sum(credits) AS total
- 2FROM courses
- 3GROUP BY dept
- 4ORDER BY dept;
| code | dept | credits | instructor_id | title |
|---|---|---|---|---|
| CS101 | CS | 4 | 1 | Intro to Programming |
| CS201 | CS | 4 | 2 | Data Structures |
| CS301 | CS | 4 | 1 | Databases |
| CS350 | CS | 4 | 2 | Operating Systems |
| CS401 | CS | 4 | 3 | Database Internals |
| CS499 | GEN | 6 | null | Senior Thesis |
| HIST101 | HIST | 3 | 7 | History of Computing |
| MATH101 | MATH | 4 | 4 | Calculus I |
| MATH201 | MATH | 3 | 5 | Discrete Math |
| MATH301 | MATH | 3 | 4 | Linear Algebra |
| PHYS101 | PHYS | 4 | 6 | Mechanics |
| PHYS201 | PHYS | 4 | 6 | Electromagnetism |
FROM hands over all 12 rows.
+ title to ask for a column that has many values per bucket, and see what postgres says. every table is a real intermediate result from school's 12 courses.a few things to notice. the 12 rows never change, only where they sit: GROUP BY doesn't throw anything away (that's HAVING's job). two keys make a bucket per combination, so MATH splits into its 3-credit and 4-credit courses. and with no GROUP BY at all, an aggregate still works: the whole table is one bucket, and you get one row.
buckets are made by equality
rows land in the same bucket when their keys are equal. "equal" here has one twist you've met before: two NULLs count as the same key. the senior thesis has no instructor, so GROUP BY instructor_id gives it a bucket of its own, labelled null. the shop's three products with no category do the same:
SELECT category, count(*) AS products
FROM products
GROUP BY category
ORDER BY category NULLS FIRST;| categorytext | productsint8 |
|---|---|
| null | 3 |
| audio | 21 |
| bath | 27 |
| books | 12 |
| games | 14 |
| garden | 15 |
| kitchen | 19 |
| office | 26 |
| outdoor | 22 |
| pets | 17 |
| toys | 24 |
11 buckets, the NULL one holding 3. that's the split personality of NULL: NULL = NULL is unknown, but sorting rows into piles needs every row to land somewhere, so the NULLs share one.
notice the ORDER BY, too. GROUP BY makes buckets, it doesn't line them up. postgres often builds them with a hash table, and a hash table has no order:
EXPLAIN (COSTS OFF)
SELECT status, count(*) FROM orders GROUP BY status ORDER BY status;HashAggregate makes the buckets, and the Sort on top is there only because the query asked for ORDER BY. leave it out and the six statuses come back in whatever order the hash table holds them. (aggregation algorithms shows the sort-based way postgres can group, too.)
grouped or aggregated
after GROUP BY, a row is a bucket. a column can appear in SELECT if it has exactly one value per bucket. two kinds of thing qualify:
- the key. every row in the dept bucket has the same dept, by construction.
- an aggregate.
count(*),sum(credits),min(title): each folds the bucket's values into one. (aggregate functions has the whole family.)
anything else would be several values fighting for one cell, so postgres refuses before it reads a single row.
SELECT dept, title, count(*) AS courses
FROM courses
GROUP BY dept;the real error, with the SQLSTATE that reading an error taught you to look for (42803):
SELECT dept, title, count(*) AS courses
FROM courses
GROUP BY dept;three ways out, and they mean different things. put title in GROUP BY, and every course becomes its own bucket (probably not what you wanted). or say which title you mean, with an aggregate: the first one alphabetically, or all of them glued together.
SELECT dept,
count(*) AS courses,
min(title) AS first_title,
string_agg(title, ', ' ORDER BY title) AS titles
FROM courses
GROUP BY dept
ORDER BY dept;| depttext | coursesint8 | first_titletext | titlestext |
|---|---|---|---|
| CS | 5 | Data Structures | |
| GEN | 1 | Senior Thesis | Senior Thesis |
| HIST | 1 | History of Computing | History of Computing |
| MATH | 3 | Calculus I | Calculus I, Discrete Math, Linear Algebra |
| PHYS | 2 | Electromagnetism | Electromagnetism, Mechanics |
string_agg with an ORDER BY inside it keeps the glued list in a fixed order, which is the same lesson as ever: no ORDER BY, no promised order.
group by the key, not the label
there's one more way to get a column into SELECT: group by the table's primary key. a primary key picks out one row, so every other column of that table has exactly one value per bucket, and postgres lets you select them without listing them. (functional dependencies is the name for this.)
it matters more than it sounds. the shop has two different customers called Sam Lee:
- 1SELECT c.name, count(*) AS orders
- 2FROM customers AS c
- 3JOIN orders AS o ON o.customer_id = c.id
- 4WHERE c.name IN ('Sam Lee', 'Ada Lovelace')
- 5GROUP BY c.name
- 6ORDER BY c.name;
| nametext | ordersint8 |
|---|---|
| Ada Lovelace | 7 |
| Sam Lee | 37 |
grouped by name, the two Sam Lees fall into one bucket: 37 orders, and no way to tell whose.
name, Toronto's Sam and Seoul's Sam become one bucket of 37 orders. by c.id, they're two people again, and c.city is allowed in SELECT without being grouped.a name is a label, not an identity. group by the key (and select the name next to it), or two people's orders end up in one total and nobody can tell.
grouping by an expression
the key doesn't have to be a column. any expression works, and the bucket is "every row where it comes out the same". date_trunc('month', ordered_at) turns every timestamp into the first moment of its month, so orders land in one bucket per month:
SELECT date_trunc('month', ordered_at)::date AS month, count(*) AS orders
FROM orders
GROUP BY date_trunc('month', ordered_at)
ORDER BY month
LIMIT 3;| monthdate | ordersint8 |
|---|---|
| 2025-07-01 | 858 |
| 2025-08-01 | 858 |
| 2025-09-01 | 830 |
858 orders in july 2025, the first bucket. a timestamptz is cut into months in the session's time zone, which on this page is UTC: on a server in Tokyo the midnight boundaries move, and so would a few orders. (timestamptz is that story.) GROUP BY can also name a SELECT alias or position in postgres, as in GROUP BY month or GROUP BY 1; the logical order explains why that's an extension and where it gets confusing.
no GROUP BY, one bucket
an aggregate without GROUP BY doesn't fail. it treats the whole table as one bucket and returns one row. so the rule still applies: a plain column next to an aggregate needs a GROUP BY to tell it what its buckets are.
SELECT dept, count(*) AS courses FROM courses;and GROUP BY without any aggregate is a perfectly good way to get one row per different value. it's the same answer as SELECT DISTINCT dept FROM courses, and postgres often runs both the same way (DISTINCT).
one level deeperwhat mysql and sqlite do instead
the standard says a selected column must be grouped, aggregated, or functionally dependent on the grouped columns, which is the rule postgres follows. not everyone was always that strict.
mysql used to accept SELECT dept, title ... GROUP BY dept and return a title from some row of each bucket. since 5.7.5 the ONLY_FULL_GROUP_BY mode is on by default and the query fails like it does here, but servers that switch the mode off still exist (mysql's GROUP BY handling). sqlite still accepts these "bare columns": each one gets a value from an arbitrary row of the bucket, except when the query uses min() or max(), where it comes from the row that had the minimum or maximum (sqlite's SELECT). handy when you know about it, and a source of quietly wrong reports when you don't.
keylines
- GROUP BY turns rows into buckets, one per different key, and hands on one row per bucket.
- a selected column must be grouped, aggregated, or decided by a grouped primary key.
- NULL keys share one bucket. buckets come back in no order unless you ORDER BY.
- the key can be any expression: a month, a first letter, a lower-cased email.
- group by the key, not the label: two Sam Lees are still two people.