sqlstreak

SQL error

each UNION query must have the same number of columns

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

Every SELECT in a UNION must return the same number of columns, in the same order and compatible types. Add the missing column, or a placeholder like NULL AS city.

The exact messages

  • PostgreSQLERROR: each UNION query must have the same number of columns
  • SQLitedo not have the same number of result columns

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. LINE gives the line it was reading when it gave up, and the ^ marks the exact spot.

ERROR:  each UNION query must have the same number of columns
LINE 3: SELECT name FROM staff;
               ^

SQLite 3.54.1 reports the same mistake as SELECTs to the left and right of UNION do not have the same number of result columns, with no line number: look for the word or column it names.

Why it happens

One side has an extra or missing column

Count the columns on each side. Columns are matched by position, not by name.

SELECT * on tables with different shapes

Two tables rarely have identical columns. List the columns explicitly.

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
SELECT name, city FROM customers
UNION
SELECT name FROM staff;
Fixed
SELECT name, city FROM customers
UNION
SELECT name, city FROM staff;

Both sides now return name and city. If a table lacks a column, select NULL AS city in its place.

The fix returns, PostgreSQL: first 6 of 18 rows

namecity
Omar HaddadAustin
Diego SantosDenver
Yuki TanakaAustin
Ivan PetrovDenver
Lia MoreauDenver
Ellie ParkDenver

The fix returns, SQLite: first 6 of 18 rows

namecity
Ben CarterAustin
Diego SantosDenver
Ellie ParkDenver
Ivan PetrovDenver
Jonah ReedDenver
Lena FischerAustin

Experiment with it: PostgreSQL playground·SQLite playground

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: SQL UNION vs UNION ALL, INTERSECT and EXCEPT.