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

When using the UNION operator in MariaDB, you may encounter the following error: “ERROR 1222 (21000): The used SELECT statements have a different number of columns”.

This error occurs when the number of columns returned by each SELECT statement is different.

The way to fix this is to ensure that 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 solution 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;

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

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

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;

This could also return different results to the other examples.