42803
PostgreSQLERRORNotableSyntax Error or Access Rule ViolationHIGH confidence

grouping error

What this means

SQLSTATE 42803 is raised when a column referenced in the SELECT list or HAVING clause is neither an aggregate function nor part of the GROUP BY clause. This violates SQL grouping rules.

Why it happens
  1. 1A non-aggregated column in the SELECT list is not listed in the GROUP BY clause
  2. 2A HAVING clause references a column that is not in GROUP BY and not wrapped in an aggregate
How to reproduce

SELECT with a non-aggregated column missing from GROUP BY.

trigger — this will error
trigger — this will error
SELECT department, name, COUNT(*)
FROM employees
GROUP BY department;
-- name is not in GROUP BY or an aggregate

expected output

ERROR:  column "employees.name" must appear in the GROUP BY clause or be used in an aggregate function

Fix 1

Add the column to GROUP BY

WHEN When the column should be part of the grouping key.

Add the column to GROUP BY
SELECT department, name, COUNT(*)
FROM employees
GROUP BY department, name;

Why this works

Adding name to GROUP BY makes it part of the group identifier, satisfying the SQL grouping rule.

Fix 2

Wrap the column in an aggregate function

WHEN When you want one representative value from the group.

Wrap the column in an aggregate function
SELECT department, MAX(name), COUNT(*)
FROM employees
GROUP BY department;

Why this works

Aggregate functions (MAX, MIN, STRING_AGG, etc.) reduce multiple values to one, which is valid in a grouped SELECT.

Sources
Official documentation ↗

Class 42 — Syntax Error or Access Rule Violation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors