Fix “ERROR 1222 (21000): The used SELECT statements have a different number of columns” when using UNION in MySQL

If you’re getting “ERROR 1222 (21000): The used SELECT statements have a different number of columns” when using the UNION clause in a MySQL query, it’s probably because the number of columns returned by each SELECT statement is different.

For example, the first SELECT statement might return two columns, but the second SELECT statement returns three.

To fix this issue, make sure both SELECT statements return the same number of columns.

Example of Error

Here’s an example of code that produces the error:

SELECT TeacherName FROM Teachers
UNION
SELECT StudentId, StudentName FROM Students;

Result:

ERROR 1222 (21000): The used SELECT statements have a different number of columns

Here, the first SELECT statement returns one column (TeacherName), but the second SELECT statement returns two columns (StudentId and StudentName).

Solution

The way to fix this issue is to ensure both SELECT statements return the same number of columns

So using the above example, we can either remove the extra column from our second SELECT statement:

SELECT TeacherName FROM Teachers
UNION
SELECT StudentName FROM Students;

Result:

+-------------+
| TeacherName |
+-------------+
| Warren      |
| Ben         |
| Cathy       |
| Bill        |
| Faye        |
| Jet         |
| Spike       |
| Ein         |
+-------------+

Or we can add another column to the first SELECT statement:

SELECT TeacherId, TeacherName FROM Teachers
UNION
SELECT StudentId, StudentName FROM Students;

Result:

+-----------+-------------+
| TeacherId | TeacherName |
+-----------+-------------+
|         1 | Warren      |
|         2 | Ben         |
|         3 | Cathy       |
|         4 | Cathy       |
|         5 | Bill        |
|         6 | Bill        |
|         1 | Faye        |
|         2 | Jet         |
|         3 | Spike       |
|         4 | Ein         |
|         5 | Warren      |
+-----------+-------------+

Be mindful that you can get different results depending on which option you choose. This is because UNION returns distinct rows by default. When we add another column, there’s a possibility that a previously duplicate row now becomes a unique row, depending on the value in the extra column.

We can also use UNION ALL, which returns duplicate values:

SELECT TeacherId, TeacherName FROM Teachers
UNION ALL
SELECT StudentId, StudentName FROM Students;

Result:

+-----------+-------------+
| TeacherId | TeacherName |
+-----------+-------------+
|         1 | Warren      |
|         2 | Ben         |
|         3 | Cathy       |
|         4 | Cathy       |
|         5 | Bill        |
|         6 | Bill        |
|         1 | Faye        |
|         2 | Jet         |
|         3 | Spike       |
|         4 | Ein         |
|         5 | Warren      |
|         6 | Bill        |
+-----------+-------------+