Diagnostic Queries
Symptoms
The branches of a UNION (or INTERSECT/EXCEPT) returned different numbers of columns. Set operations require matching column counts, so PostgreSQL raises SQLSTATE 42601 (syntax_error).
- Two SELECTs in a UNION have unequal column counts.
- Common after adding/removing a column from one branch.
- Applies to UNION, INTERSECT, and EXCEPT.
What the server log shows
ERROR: each UNION query must have the same number of columns
Why PostgreSQL raises this — what the manual says
Section 7.4 Combining Queries (UNION, INTERSECT, EXCEPT):
“which means that they return the same number of columns and the corresponding columns have compatible data types, as described in Section 10.5.”
Set operations align results column-by-column, so each branch must produce the same number of columns of compatible types. A mismatch in count makes alignment impossible and PostgreSQL reports 42601.
Common causes
- One SELECT lists more/fewer columns than the other.
SELECT *on tables with different column counts.- An edit to one branch that wasn’t mirrored in the other.
How to fix it
- Make every branch select the same number of columns in the same order.
- Avoid
SELECT *in set operations; list columns explicitly. - Add placeholder/NULL columns to align counts when intentional.
Related & next steps
Reference: PostgreSQL 18 Section 7.4 “Combining Queries”.
Thanks — noted. This helps keep the database accurate.