Why it happens: UNION has a different number of columns
SELECT id, name
FROM customers
UNION ALL
SELECT id, name, city
FROM suppliers;The first query returns two columns and the second returns three. The rows from customers have no third position to combine with city.
Check the result with small data
The two queries select exactly two columns in the same order.
WITH students(id, name) AS (VALUES (1,'Amy')),
teachers(id, name) AS (VALUES (2,'Liam'))
SELECT id, name FROM students
UNION ALL SELECT id, name FROM teachers;| id | name |
|---|---|
| 1 | Amy |
| 2 | Liam |
UNION ALL can combine them because the structure matches. If the second query returned only name, the operation would be invalid.
Check your understanding: What would you add to a branch that lacks an optional column?
Show answer
A NULL column with the alias for that position, for example NULL AS city, so that both branches have the same columns.
How to fix it in SQL
Do not add any old column just to make the count match. Decide what each position means in the final result. If you want one list of entities with where each came from, both branches can return id, name and a source label:
SELECT id, name, 'customer' AS source
FROM customers
UNION ALL
SELECT id, name, 'supplier' AS source
FROM suppliers;| id | name | source |
|---|---|---|
| 1 | Amy | customer |
| 8 | Delta SA | supplier |
How to check it
Run each branch on its own and compare the number, order, meaning and type of its columns.
How to avoid it next time
Avoid SELECT * when the combined result needs a stable structure.
Related cases worth checking
Having three columns on each side does not, on its own, make a well-designed union. The first column is combined with the first, the second with the second, and so on. PostgreSQL requires compatible types; MySQL works out the result type from the values in the matching columns. Do not mix, say, a date with an identifier just because they sit in the same position.
The visible names in the result are not matched by name either. In engines such as PostgreSQL and MySQL, the output names come from the first branch; what matters for the combination is position and compatibility.