Fix “ERROR 1054 (42S22): Unknown column ‘…’ in ‘on clause'” in MariaDB

If you’re getting an error that reads something like “ERROR 1054 (42S22): Unknown column ‘tab.ColName’ in ‘on clause”” in MariaDB, here are three likely causes:

  • The column doesn’t exist.
  • You’re trying to reference an aliased column by its column name.
  • Or it could be the other way around. You could be referencing the column with an alias that was never declared.

If a column has an alias, then you must use that alias when referencing it in any ON clause when doing a join against two or more tables. Conversely, if you reference a column by an alias, then you need to ensure that the alias is actually declared in the first place.

Example 1

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

SELECT 
    c.CatId,
    c.CatName
FROM Cats c
INNER JOIN Dogs d
ON c.DogName = d.DogName;

Result:

ERROR 1054 (42S22): Unknown column 'c.DogName' in 'on clause'

Here I accidentally used c.DogName in the ON clause when I meant to use c.CatName.

In this case, the fix is simple. Use the correct column name:

SELECT 
    c.CatId,
    c.CatName
FROM Cats c
INNER JOIN Dogs d
ON c.CatName = d.DogName;

Example 2

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

SELECT 
    CatId,
    CatName
FROM Cats
INNER JOIN Dogs d
ON c.CatName = d.DogName;

Result:

ERROR 1054 (42S22): Unknown column 'c.CatName' in 'on clause'

Here I referenced a non-existent alias in the ON clause. I used c.CatName to refer to the CatName column in the Cats table. The only problem is that the Cats table doesn’t have an alias.

To fix this issue, all we have to do is provide an alias for the Cats table:

SELECT 
    CatId,
    CatName
FROM Cats c
INNER JOIN Dogs d
ON c.CatName = d.DogName;

Alternatively, we could remove all references to the alias, and just use the full table name:

SELECT 
    CatId,
    CatName
FROM Cats
INNER JOIN Dogs
ON Cats.CatName = Dogs.DogName;

One thing I should point out is that, in this example we didn’t prefix the column names in the SELECT list with the alias. If we had done that, we would have seen the same error, but with a slightly different message:

SELECT 
    c.CatId,
    c.CatName
FROM Cats
INNER JOIN Dogs d
ON c.CatName = d.DogName;

Result:

ERROR 1054 (42S22): Unknown column 'c.CatId' in 'field list'

In this case, it detected the unknown columns in the field list before it found the one in the ON clause. Either way, the solution is the same.

Example 3

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

SELECT 
    c.CatId,
    c.CatName
FROM Cats c
INNER JOIN Dogs d
ON Cats.CatName = d.DogName;

Result:

ERROR 1054 (42S22): Unknown column 'Cats.CatName' in 'on clause'

In this case, an alias was declared for the Cats table, but I didn’t use that alias in the ON clause.

The solution here, is to use the alias instead of the table name:

SELECT 
    c.CatId,
    c.CatName
FROM Cats c
INNER JOIN Dogs d
ON c.CatName = d.DogName;