MySQL Error 1222: UNION SELECTs Return Different Column Counts
Fix MySQL Error 1222 by aligning each UNION query’s column count and position; distinguish column-count errors from type conversion.
On this page
MySQL Error 1222 (21000, ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT) means query blocks combined by UNION, INTERSECT, or EXCEPT return different numbers of columns. Each corresponding column is matched by position. See the MySQL Error 1222 reference and set-operations documentation.
Count the columns in each query block
This query returns three columns in the first SELECT and two in the second, so MySQL reports Error 1222:
SELECT id, name, email FROM users
UNION
SELECT id, username FROM admins;
Count every expression in each SELECT list, including expressions, constants, and NULL placeholders. Column aliases and names do not need to match; the number and positions must.
Add a meaningful placeholder or remove the extra column
If the second source has no email value, supply a placeholder in the third position:
SELECT id, name, email FROM users
UNION
SELECT id, username, NULL FROM admins;
If the combined result should not include email, remove that column from every query block instead. Use an expression such as CAST(NULL AS CHAR) when a string placeholder’s result type needs to be explicit.
Avoid SELECT * in a UNION: a schema change can silently add or reorder columns in one table and cause Error 1222. List the columns explicitly in every query block.
Check column types separately
Different data types in corresponding positions are a separate issue from Error 1222. MySQL determines result-column types using the values from all query blocks and can convert them; this does not necessarily produce a runtime error. If you require a specific common type, cast each expression explicitly and validate that the conversion is appropriate. See MySQL’s type-conversion rules.
The result column names come from the first query block. Aliases in later SELECT statements do not rename the output columns. See result column names and data types for set operations.
Check UNION ALL and nested query blocks
UNION ALL keeps duplicate rows, while UNION removes them; both require the same number of columns in every query block. If a statement contains several set operators or nested query blocks, compare each adjacent pair rather than only the first and last SELECT.
Distinguish an INSERT column-count error
If the message is Error 1136 (21S01), MySQL is reporting that an INSERT target column list and its values or SELECT output have different counts. That is different from Error 1222 for set-operation query blocks. See MySQL Error 1136 troubleshooting.
For the full syntax, see MySQL UNION and SELECT. Browse other issues in MySQL Error Troubleshooting.