Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readSQL
#PostgreSQL#SQL#Queries#Errors
A Postgres group crate holding one cyan row per group, an amber aggregate card and a split row beside it

Introduction & Quick Summary

text
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 in min()/max().
  • You want the latest (or first) row per group — this is not a GROUP BY question. Use DISTINCT ON, a window function, or LATERAL.
  • You group by a unique key — Postgres infers functional dependency and lets you select the other columns of that table.
IntentWrong approachRight approach
Total per customerSELECT customer_id, created_at, count(*)min(created_at) or drop the column
Latest order per customermax(created_at) in the same selectDISTINCT ON or row_number()
Full latest rowGROUP BY customer_id, idWindow or LATERAL, not GROUP BY
One column per group key setGROUP BY 1 positionFine, but fragile after edits
Counting distinct valuescount(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 clause
SELECT 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

TechniqueReturnsCostBest for
GROUP BY + aggregateOne row per group, aggregatedOne sort/hashTotals, counts, min/max
GROUP BY primary keyAll columns of that tableSameGrouping by id
DISTINCT ON (key)One full row per keySort by key then columnsLatest row, Postgres-specific
row_number() OVER (PARTITION BY ...)Ranked rows, filtered outsideWindow sortTies, top-N per group
LATERAL subqueryOne row per outer rowNested loopPer-row lookups with LIMIT
array_agg in GROUP BYAll values in one cellMemory per groupSmall, bounded lists
DatabaseDefault behaviorNote
PostgreSQLStrictError 42803
MySQL 5.7+ONLY_FULL_GROUP_BY onSame error, different message
MySQL 5.6 and olderArbitrary rowSilent wrong results
SQLiteArbitrary rowBare columns allowed
SQL ServerStrictRequires 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_BY switch; the only options are correct SQL or an arbitrary-value workaround.
  • GROUP BY on the wrong key set. Grouping by customer_id, created_at removes the error and multiplies the rows; compare the row count with the intent before shipping.
  • count(column) versus count(*). count(column) skips nulls, so a "total rows" report silently undercounts when that column is nullable.
  • Aggregates in WHERE. WHERE count(*) > 1 is a syntax error; the same predicate belongs in HAVING.
  • Functional dependency across joins. It applies per table; GROUP BY c.id does not license selecting o.created_at from a joined table.
  • GROUPING SETS / ROLLUP output. 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 documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.