Incident Response

PostgreSQL: column must appear in the GROUP BY clause or be used in an aggregate function

The query worked in MySQL, or it worked until someone added one more column, and now PostgreSQL refuses it. The error is not pedantry: it stops a query that has no single correct answer. Here is what PostgreSQL allows, the four real fixes, and what changes when the table has hundreds of millions of rows.

· 14 min read · AG Data Team

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:

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.

  1. 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().
  2. 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.
  3. 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.
  4. 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 ON or 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 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

PostgreSQL Errors SQL Performance
Work with us

Reports slow or broken after a migration?

We rewrite heavy GROUP BY and reporting queries for PostgreSQL, check the plans on production-sized data and tune memory so they stop spilling to disk.

Get in touch More from the blog