Diagnostic Queries
Symptoms
A GROUP BY used a positional number that does not correspond to a column in the select list. PostgreSQL raises SQLSTATE 42P10 (invalid_column_reference).
- GROUP BY n where n exceeds the number of output columns.
- Positional grouping references the SELECT list by index.
- Common after editing the select list.
What the server log shows
ERROR: GROUP BY position 5 is not in select list
Why PostgreSQL raises this — what the manual says
As Section 7.2.3 The GROUP BY and HAVING Clauses explains:
A GROUP BY item written as a positional number refers to the ordinal position of an output column in the select list; a number that does not correspond to any select-list column (for example GROUP BY 5 when only three columns are selected) is rejected.
Positional GROUP BY refers to the n-th item in the select list. When n is larger than the number of output columns (or otherwise invalid), there is no column to group by and PostgreSQL reports 42P10.
Common causes
- A position number greater than the count of select-list items.
- The select list changed but the positions did not.
- Off-by-one positional references.
How to fix it
- Use a valid position within the select list range.
- Group by the column name/expression instead of a number.
- Recount the select-list items after edits.
Related & next steps
Reference: PostgreSQL 18 Section 7.2 “Table Expressions”.
Thanks — noted. This helps keep the database accurate.