grouping error
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.
- 1A non-aggregated column in the SELECT list is not listed in the GROUP BY clause
- 2A HAVING clause references a column that is not in GROUP BY and not wrapped in an aggregate
SELECT with a non-aggregated column missing from GROUP BY.
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.
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.
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.
Class 42 — Syntax Error or Access Rule Violation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev