Diagnostic Queries
Symptoms
An ORDER BY used a positional number outside the range of the select list. PostgreSQL raises SQLSTATE 42P10 (invalid_column_reference).
- ORDER BY n where n exceeds the number of output columns.
- Positional ordering references the SELECT list by index.
- Common after changing the select list.
What the server log shows
ERROR: ORDER BY position 4 is not in select list
Why PostgreSQL raises this — what the manual says
Section 7.5 Sorting Rows (ORDER BY):
“A sort_expression can also be the column label or number of an output column”
Positional ORDER BY refers to the n-th select-list item. When n exceeds the number of output columns, there is no column at that position and PostgreSQL reports 42P10.
Common causes
- A position number larger than the select-list length.
- The select list shrank but ORDER BY positions did not.
- Off-by-one ordinal references.
How to fix it
- Use a position within the valid range.
- Order by the column name/expression instead of a number.
- Recount the select-list items after edits.
Related & next steps
Reference: PostgreSQL 18 Section 7.5 “Sorting Rows”.
Thanks — noted. This helps keep the database accurate.