ERROR: column "..." must appear in the GROUP BY clause or be used in an aggregate function means your query groups rows, but the select list (or HAVING, or ORDER BY) also asks for a column that can have many different values inside one group. PostgreSQL does not know which of those values you want, so it refuses to guess.
app=> SELECT c.id, c.name, o.created_at, sum(o.amount)
app-> FROM customers c JOIN orders o ON o.customer_id = c.id
app-> GROUP BY c.id;
ERROR: column "o.created_at" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT c.id, c.name, o.created_at, sum(o.amount)
^
The SQLSTATE is 42803, grouping_error in the error codes table. A close relative from the same check in parse_agg.c is subquery uses ungrouped column "..." from outer query: same problem, with the ungrouped column referenced from inside a subquery.
Why PostgreSQL refuses
A customer has many orders, so in the example above every group (one customer) has many created_at values. Returning one of them at random would give a result that changes between runs and between plans. The SELECT reference states the rule: when GROUP BY or an aggregate is present, select list expressions may not refer to ungrouped columns except inside aggregate functions, or when the column is functionally dependent on the grouped columns.
Notice that c.name did not cause the error. That is the functional dependency part, and it is narrower than many people expect:
- Only a primary key counts. PostgreSQL recognises functional dependency only when a table's primary key is in the
GROUP BYlist. AUNIQUEconstraint, even on aNOT NULLcolumn, is not enough. - It works per table. Grouping by
c.idunlocks every column ofcustomers, but not columns oforders. - It needs a table with a primary key. The check in
parse_agg.clooks for the primary key constraint of a relation inFROM. Views and subqueries have none, so grouping by their key column does not unlock their other columns.
The fixes, by what you actually want
Every fix starts with one question: for this group, which value of the column do you want? The answer picks the fix.
- One computed value per group. You wanted the latest date, the total, the count. Wrap the column in an aggregate:
max(),min(),sum(),count(),string_agg(),array_agg(). - Separate rows for each value. You wanted one row per customer and per day. Add the column, or the expression, to
GROUP BY. The documentation allows an input column, an output column name or its ordinal number there. - Any value, because they are all the same. The column really is constant within the group (a currency per customer, for example) but no constraint proves it. PostgreSQL 16 added the aggregate
any_value()(release notes); the aggregate functions page describes it as returning an arbitrary value from the non-null inputs. Use it only when the values truly are equal. - A whole row from each group. You wanted the details of the latest order, not just its date. That is not grouping at all; use
DISTINCT ONor a window function, below.
-- 1. aggregate it: what you usually meant was "the latest order"
SELECT c.id, c.name, max(o.created_at) AS last_order, sum(o.amount) AS total
FROM customers c JOIN orders o ON o.customer_id = c.id
GROUP BY c.id; -- c.name is fine: c.id is the primary key of customers
-- 2. group by it: one row per customer AND per day
SELECT c.id, c.name, o.created_at::date AS day, sum(o.amount) AS total
FROM customers c JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, day; -- an output column name works in GROUP BY
-- 3. PostgreSQL 16+: any value will do (all values in the group are equal)
SELECT o.customer_id, any_value(o.currency) AS currency, sum(o.amount)
FROM orders o
GROUP BY o.customer_id;
For "the latest row per group", DISTINCT ON is the short PostgreSQL way. It is an extension of the SQL standard, it keeps the first row of each set, and its expressions must match the leftmost ORDER BY expressions. Without that ORDER BY the "first row" is unpredictable. A row_number() window is longer but portable, and changes to top 3 by editing one number.
-- the whole latest order per customer: DISTINCT ON
SELECT DISTINCT ON (o.customer_id) o.customer_id, o.id, o.created_at, o.amount
FROM orders o
ORDER BY o.customer_id, o.created_at DESC;
-- the same with a window function (portable, also gives top-N)
SELECT customer_id, id, created_at, amount
FROM (SELECT o.*, row_number() OVER (PARTITION BY customer_id
ORDER BY created_at DESC) AS rn
FROM orders o) t
WHERE rn = 1;
Do not just paste every column into GROUP BY. It removes the error and quietly changes the result: if created_at joins the grouping key, one customer becomes many rows and the totals split. Decide which value you need first, then pick the fix.
Coming from MySQL
This error is one of the first a MySQL to PostgreSQL migration hits. MySQL's GROUP BY handling has the ONLY_FULL_GROUP_BY SQL mode, enabled by default in current versions, which rejects the same queries PostgreSQL does. Applications that disabled it got queries where, in MySQL's own words, the server is free to choose any value from each group, so unless the values are the same, the result is nondeterministic. ORDER BY does not influence that choice.
So a query that "worked" in MySQL may have been returning arbitrary values for years. When porting, do not reach for any_value() by reflex just because MySQL has ANY_VALUE() too. Check the data first: if the values differ within a group, the old report was already wrong, and the right port is an aggregate or DISTINCT ON.
What changes on large tables
On a small table every fix runs instantly. On a table with hundreds of millions of rows the choice of fix decides whether the query takes seconds or an hour, and whether it writes gigabytes of temporary files.
- Aggregate first, join the details later. Grouping a huge fact table by a wide key (customer id plus name, email, country...) makes each group bigger to hash or sort. Grouping by the narrow key in a subquery and joining the descriptive columns afterwards keeps the expensive step small. In our experience this is one of the cheapest rewrites for slow reports.
- Watch hash aggregates spill. Since PostgreSQL 13, a hash aggregate that exceeds
work_memtimeshash_mem_multiplierspills to disk instead of growing without limit. The multiplier defaults to 2.0 since PostgreSQL 15. InEXPLAIN (ANALYZE)look at the HashAggregate line: more than one batch and a non-zero Disk Usage mean it spilled. Raisework_memfor that report withSET LOCAL, not for every connection on the server. - DISTINCT ON sorts everything without an index. On a big table it means a full sort of all rows. An index on
(customer_id, created_at DESC)lets PostgreSQL read rows in the right order, and aLATERAL ... LIMIT 1per customer can use it for a short index lookup per group. In our experience the lateral form wins when groups are few and large, and the sort-based forms win when there are many small groups; check the plan on real data volumes. - The primary key rule creates a dependency. When a query relies on functional dependency,
parse_agg.crecords a dependency on the primary key constraint, because the query stops being valid without it; for a view it is stored with the view. When you later swap a primary key, for example during an int to bigint migration on a big table, those views block the drop. Cannot drop because other objects depend on it shows how to find and rebuild them. - Plans change with volume. The planner picks between hash and sort aggregation from statistics. A query that used a hash aggregate on last year's data can switch to a sort, or start spilling, as the table grows. Review the plans of your heaviest reports periodically, not only when they break.
-- aggregate the big table first, join the details afterwards
SELECT c.id, c.name, c.email, c.country, t.orders, t.total
FROM (SELECT customer_id, count(*) AS orders, sum(amount) AS total
FROM orders
WHERE created_at >= now() - interval '30 days'
GROUP BY customer_id) t
JOIN customers c ON c.id = t.customer_id;
-- latest order per customer with an index instead of a full sort
CREATE INDEX CONCURRENTLY orders_cust_created_idx
ON orders (customer_id, created_at DESC);
SELECT c.id, l.id AS order_id, l.created_at
FROM customers c
CROSS JOIN LATERAL (SELECT o.id, o.created_at FROM orders o
WHERE o.customer_id = c.id
ORDER BY o.created_at DESC
LIMIT 1) l;
-- excerpt of EXPLAIN (ANALYZE) output; your numbers will differ
HashAggregate (actual time=... rows=... loops=1)
Group Key: customer_id
Batches: 5 Memory Usage: 8241kB Disk Usage: 162336kB
-- give one heavy report more memory instead of the whole server
BEGIN;
SET LOCAL work_mem = '256MB';
SELECT ...;
COMMIT;
Key takeaways
- The error means a column has several values per group and PostgreSQL will not pick one for you.
- Grouping by a table's primary key unlocks that table's other columns; unique constraints, views and subqueries do not.
- Pick the fix by intent: an aggregate, a wider
GROUP BY,any_value()in PostgreSQL 16+, orDISTINCT ON/row_number()for whole rows. - Queries ported from MySQL with
ONLY_FULL_GROUP_BYoff may have returned arbitrary values; check the data before porting. - On large tables aggregate on narrow keys first, watch for spilling hash aggregates and index the per-group ordering.