sqlstreak

SQL error

UNION types text and integer cannot be matched

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

Short answer

UNION stacks columns by position, so each position needs the same type on both sides. A text column lined up with an integer column usually means the columns are in the wrong order or the wrong one was picked.

The exact messages

  • PostgreSQLERROR: UNION types text and integer cannot be matched
  • SQLiteNo error, but a silent surprise: see below.

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:  UNION types text and integer cannot be matched
LINE 3: SELECT id FROM staff;
               ^

Why it happens

Columns in a different order

SELECT name, id … UNION SELECT id, name … puts ids under names. UNION matches by position, never by column name.

The wrong column on one side

Picking id where you meant name. Read both SELECT lists side by side.

You really need mixed values

Then convert explicitly, CAST(id AS TEXT), so the result column is text on both sides.

Reproduce it, then fix it

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

Broken
SELECT name FROM customers
UNION
SELECT id FROM staff;
Fixed
SELECT name FROM customers
UNION
SELECT name FROM staff;

Text under text: both sides now return names.

The fix returns, PostgreSQL: first 6 of 18 rows

name
Lia Moreau
Ben Carter
Diego Santos
Ellie Park
Maya Ortiz
Yuki Tanaka

The fix returns, SQLite: first 6 of 18 rows

name
Ben Carter
Diego Santos
Ellie Park
Ivan Petrov
Jonah Reed
Lena Fischer

Experiment with it: PostgreSQL playground·SQLite playground

What SQLite does instead

SQLite stacks the values anyway, so names and numbers end up mixed in one column. No error, just a result that makes no sense.

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.