Postgres: column must appear in the GROUP BY clause
A grouped query needs one value per group. Aggregate the column, add it to GROUP BY, or use DISTINCT ON and windows for latest-row-per-group needs.

Introduction & Quick Summary
ERROR: column "orders.created_at" must appear in the GROUP BY clause
or be used in an aggregate function
LINE 1: SELECT customer_id, created_at, count(*) FROM orders GROUP BY customer_id;
^
SQL state: 42803 (grouping_error)A grouped query returns one row per group. Every expression in the select list must therefore be constant across that group: a grouping column, an aggregate, or a function of those. created_at varies inside each customer's group, so Postgres refuses to pick a value for you.
Three correct answers, depending on what the row should mean:
- One arbitrary value from the group is acceptable — add the column to
GROUP BY, or wrap it inmin()/max(). - You want the latest (or first) row per group — this is not a
GROUP BYquestion. UseDISTINCT ON, a window function, orLATERAL. - You group by a unique key — Postgres infers functional dependency and lets you select the other columns of that table.
| Intent | Wrong approach | Right approach |
|---|---|---|
| Total per customer | SELECT customer_id, created_at, count(*) | min(created_at) or drop the column |
| Latest order per customer | max(created_at) in the same select | DISTINCT ON or row_number() |
| Full latest row | GROUP BY customer_id, id | Window or LATERAL, not GROUP BY |
| One column per group key set | GROUP BY 1 position | Fine, but fragile after edits |
| Counting distinct values | count(col) | count(DISTINCT col) |
Core Mechanics, Signatures & Reproducible Setup
SQL's grouping rule is semantic, not a Postgres quirk: after GROUP BY, the logical table has one row per group, and non-aggregated columns have no single value. Postgres implements this strictly. MySQL before 5.7 returned an arbitrary row (and still does with ONLY_FULL_GROUP_BY disabled), which is why queries copied from MySQL fail here.
The relevant parts of the grammar:
SELECT select_list
FROM ...
[WHERE ...]
GROUP BY grouping_element [, ...]
[HAVING ...]
[ORDER BY ...]A grouping_element can be a column, a positional number, an expression, GROUPING SETS, ROLLUP or CUBE. Expressions in the select list are matched against grouping elements by structural equality, so date_trunc('day', created_at) must appear in both places, not just one.
Reproduce it:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
total_cents integer NOT NULL
);
INSERT INTO orders (customer_id, total_cents) VALUES
(1, 1200), (1, 800), (2, 500);
SELECT customer_id, created_at, count(*)
FROM orders
GROUP BY customer_id;
-- ERROR: column "orders.created_at" must appear in the GROUP BY clauseSELECT customer_id, min(created_at) AS first_order, count(*) AS orders
FROM orders
GROUP BY customer_id
ORDER BY customer_id;The second query answers "how many orders and when did they start" — a real question with one row per group. The first query was ambiguous, and the error is the database asking which value you meant.
Key Comparison Table
| Technique | Returns | Cost | Best for |
|---|---|---|---|
GROUP BY + aggregate | One row per group, aggregated | One sort/hash | Totals, counts, min/max |
GROUP BY primary key | All columns of that table | Same | Grouping by id |
DISTINCT ON (key) | One full row per key | Sort by key then columns | Latest row, Postgres-specific |
row_number() OVER (PARTITION BY ...) | Ranked rows, filtered outside | Window sort | Ties, top-N per group |
LATERAL subquery | One row per outer row | Nested loop | Per-row lookups with LIMIT |
array_agg in GROUP BY | All values in one cell | Memory per group | Small, bounded lists |
| Database | Default behavior | Note |
|---|---|---|
| PostgreSQL | Strict | Error 42803 |
| MySQL 5.7+ | ONLY_FULL_GROUP_BY on | Same error, different message |
| MySQL 5.6 and older | Arbitrary row | Silent wrong results |
| SQLite | Arbitrary row | Bare columns allowed |
| SQL Server | Strict | Requires all non-aggregated columns |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: Add the column when one value per group is fine
SELECT customer_id, max(created_at) AS last_order, sum(total_cents) AS cents
FROM orders
GROUP BY customer_id;min/max are the honest way to keep a timestamp in a grouped row. any_value does not exist in Postgres — the usual substitutes are min, max, or (array_agg(x))[1], and the last one is a smell that the query wants a different shape.
Case 2: The latest full row per customer
SELECT DISTINCT ON (customer_id) *
FROM orders
ORDER BY customer_id, created_at DESC, id DESC;DISTINCT ON keeps the first row of each (customer_id) group according to the ORDER BY, and the leading expressions must match the DISTINCT ON list. It is the shortest correct form in Postgres and it returns real rows, not aggregates.
SELECT customer_id, created_at, total_cents
FROM (
SELECT *, row_number() OVER (
PARTITION BY customer_id ORDER BY created_at DESC, id DESC
) AS rn
FROM orders
) t
WHERE rn = 1;The window version is portable across databases and lets you take rn <= 3 for top-N. For a handful of customers, LATERAL is often fastest with the right index:
SELECT c.id, o.created_at, o.total_cents
FROM customers c
CROSS JOIN LATERAL (
SELECT created_at, total_cents
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) o;Case 3: Functional dependency on the primary key
SELECT o.id, o.customer_id, o.created_at, count(l.id) AS lines
FROM orders o
LEFT JOIN order_lines l ON l.order_id = o.id
GROUP BY o.id;This is legal in Postgres 9.1 and later: grouping by the primary key makes every other column of that table functionally dependent, so no error. It is the cleanest fix when the group really is "one order". Grouping by a unique column of a joined table does not grant the same freedom for other joined tables.
Case 4: Aliases, positions and the HAVING split
SELECT date_trunc('day', created_at) AS day, count(*) AS orders
FROM orders
GROUP BY day
ORDER BY day;Postgres allows an output alias in GROUP BY (an extension to the standard), which keeps long expressions from being repeated. ORDER BY also accepts aliases and positions. WHERE does not — filtering on an aggregate requires HAVING:
SELECT customer_id, count(*) AS orders
FROM orders
GROUP BY customer_id
HAVING count(*) > 2;Position-based grouping (GROUP BY 1) works but breaks silently when someone reorders the select list; prefer the alias.
Case 5: Aggregating text and arrays
SELECT customer_id,
string_agg(DISTINCT status, ',' ORDER BY status) AS statuses,
array_agg(total_cents ORDER BY created_at) AS cents_in_order
FROM orders
GROUP BY customer_id;Set-returning aggregates keep detail inside one cell. They are convenient for API responses under a few hundred rows and become a memory problem at scale, where a join or a JSON aggregate is better.
Case 6: The query that needs two levels of grouping
SELECT customer_id, day, orders
FROM (
SELECT customer_id,
date_trunc('day', created_at) AS day,
count(*) AS orders
FROM orders
GROUP BY customer_id, date_trunc('day', created_at)
) daily
WHERE orders > 10;A single GROUP BY cannot both count per day and return day detail; the inner query groups, the outer filters. Trying to do both in one level produces either the 42803 error or a wrong count.
Common Compilation/Runtime Mistakes & Version Gotchas
- Disabling strictness instead of fixing the query. Postgres has no
ONLY_FULL_GROUP_BYswitch; the only options are correct SQL or an arbitrary-value workaround. GROUP BYon the wrong key set. Grouping bycustomer_id, created_atremoves the error and multiplies the rows; compare the row count with the intent before shipping.count(column)versuscount(*).count(column)skips nulls, so a "total rows" report silently undercounts when that column is nullable.- Aggregates in
WHERE.WHERE count(*) > 1is a syntax error; the same predicate belongs inHAVING. - Functional dependency across joins. It applies per table;
GROUP BY c.iddoes not license selectingo.created_atfrom a joined table. GROUPING SETS/ROLLUPoutput. These produce null-filled rows for subtotals;GROUPING(col)distinguishes a real null from a subtotal null.- Planner changes in PG 16+. Incremental sort and parallel hash aggregate change plans for large grouped queries; a query that was fast in 14 can prefer a parallel plan with different memory pressure, so check
EXPLAIN (ANALYZE, BUFFERS)after upgrades.
Format the failing statement with the SQL formatter to see which expressions are grouped, and sketch the intended result shape with the schema designer before adding columns to GROUP BY; the diff tool is useful when comparing two versions of a reporting query.
Primary references: SELECT — GROUP BY clause specifies grouping elements and functional dependency, and Appendix A — PostgreSQL Error Codes lists 42803 and its family.
Official references
primary documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
Postgres: column does not exist (SQLSTATE 42703)
42703 means the identifier you wrote is not the one that exists. Check case folding, alias scope, search_path and migration drift.
pg_dump: server version mismatch, aborting because of server version
pg_dump refuses to read a newer server. Install a matching client, run it from a container or the server host, and match pg_restore too.
Postgres RLS 42P17: infinite recursion detected in policy
A policy on members that reads members re-enters itself. A security definer function with a pinned search_path ends it and leaves the policy intact.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.