PostgreSQL: column must appear in the GROUP BY clause
ERROR: column "<t>.<col>" must appear in the GROUP BY clause or be used in an aggregate functionYour query mixes aggregated and non-aggregated columns without grouping the plain ones. Postgres needs to know how to collapse each selected column into one value per group. Add the column to GROUP BY, wrap it in an aggregate, or use DISTINCT ON.
What this error means
When a query uses an aggregate like count() or sum(), every other selected column must either be in the GROUP BY or be inside its own aggregate. Otherwise Postgres cannot tell which value to return for a group of many rows.
Developers coming from MySQL hit this often, because older MySQL let you select ungrouped columns and silently picked an arbitrary row. Postgres refuses to guess.
How to fix it
You want one row per group
List every non-aggregated selected column in GROUP BY.
SELECT customer_id, count(*)
FROM orders
GROUP BY customer_id;You only need one value of the extra column
Wrap it in an aggregate such as max() or min() so Postgres knows how to reduce it.
SELECT customer_id, max(created_at) AS last_order
FROM orders
GROUP BY customer_id;You want the whole latest row per group
DISTINCT ON returns the first row per group given an ORDER BY, which is often what people actually want here.
SELECT DISTINCT ON (customer_id) *
FROM orders
ORDER BY customer_id, created_at DESC;How to avoid it next time
- Decide up front whether you want one row per group (GROUP BY) or the latest full row per group (DISTINCT ON).
- Do not assume MySQL grouping behavior; Postgres is strict on purpose.
Frequently asked questions
Why does MySQL allow this and Postgres does not?
Older MySQL modes returned an arbitrary row for ungrouped columns. Postgres considers that ambiguous and requires you to say how each column collapses.
What is DISTINCT ON?
A Postgres feature that keeps the first row of each group as defined by an ORDER BY. It is the clean way to get the latest row per key.
Stop struggling with SQL
Use FluentDB, the AI database client for macOS.
Related errors
Part of the PostgreSQL error reference. Last reviewed 2026-07-31.