skip to content

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.

GROUP BY =
SELECT =
query.sqlstep 1: FROM
  1. 1SELECT dept, count(*) AS courses, sum(credits) AS total
  2. 2FROM courses
  3. 3GROUP BY dept
  4. 4ORDER BY dept;
the table after FROM
codedeptcreditsinstructor_idtitle
CS101CS41Intro to Programming
CS201CS42Data Structures
CS301CS41Databases
CS350CS42Operating Systems
CS401CS43Database Internals
CS499GEN6nullSenior Thesis
HIST101HIST37History of Computing
MATH101MATH44Calculus I
MATH201MATH35Discrete Math
MATH301MATH34Linear Algebra
PHYS101PHYS46Mechanics
PHYS201PHYS46Electromagnetism
(12 rows)

FROM hands over all 12 rows.

clause 1/3
real output, postgres 18.6 (PGlite 0.5.12) · group-by
pick a key and step through. the rows sort into buckets, then each bucket collapses into one row: the key in hot, plus the aggregates. switch on + 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:

sqldb=shop
SELECT category, count(*) AS products
FROM products
GROUP BY category
ORDER BY category NULLS FIRST;
output, from postgres 18.6
SELECT 11
categorytextproductsint8
null3
audio21
bath27
books12
games14
garden15
kitchen19
office26
outdoor22
pets17
toys24
(11 rows)

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:

sqldb=shop
EXPLAIN (COSTS OFF)
SELECT status, count(*) FROM orders GROUP BY status ORDER BY status;
output, from postgres 18.6
EXPLAIN
Sort Sort Key: status -> HashAggregate Group Key: status -> Seq Scan on orders

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.

predict the output
sql
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):

sqldb=school
SELECT dept, title, count(*) AS courses
FROM courses
GROUP BY dept;
output, from postgres 18.6
ERROR 42803: column "courses.title" must appear in the GROUP BY clause or be used in an aggregate function
1 │ SELECT dept, title, count(*) AS courses
at line 1, column 14

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.

sqldb=school
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;
output, from postgres 18.6
SELECT 5
depttextcoursesint8first_titletexttitlestext
CS5Data Structures
GEN1Senior ThesisSenior Thesis
HIST1History of ComputingHistory of Computing
MATH3Calculus ICalculus I, Discrete Math, Linear Algebra
PHYS2ElectromagnetismElectromagnetism, Mechanics
(5 rows)

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:

GROUP BY =
query.sql
  1. 1SELECT c.name, count(*) AS orders
  2. 2FROM customers AS c
  3. 3JOIN orders AS o ON o.customer_id = c.id
  4. 4WHERE c.name IN ('Sam Lee', 'Ada Lovelace')
  5. 5GROUP BY c.name
  6. 6ORDER BY c.name;
the result for name
nametextordersint8
Ada Lovelace7
Sam Lee37
(2 rows)

grouped by name, the two Sam Lees fall into one bucket: 37 orders, and no way to tell whose.

real output, postgres 18.6 (PGlite 0.5.12) · group-by-shop
switch the key. by 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:

2025-07858
2025-08858
2025-09830
2025-10859
2025-11830
2025-12859
2026-01859
2026-02775
2026-03859
2026-04830
2026-05859
2026-06724
orders per month, one bar per bucket. july 2025 to june 2026: february is short because february is short, and june is cut off where the data ends.
sqldb=shop
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;
output, from postgres 18.6
SELECT 3
monthdateordersint8
2025-07-01858
2025-08-01858
2025-09-01830
(3 rows)

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.

sqldb=school
SELECT dept, count(*) AS courses FROM courses;
output, from postgres 18.6
ERROR 42803: column "courses.dept" must appear in the GROUP BY clause or be used in an aggregate function
1 │ SELECT dept, count(*) AS courses FROM courses;
at line 1, column 8

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.