Mysql – Unknown column in ‘where clause’ when using an alias for a subquery in MySQL

aliasMySQLwhere

This simple query:

select exam.id as exam_id,
(select count(*) from dataset where dataset.id = exam.id) as n_dataset
from exam
where n_dataset = 0

returns the following error:

ERROR 1054 (42S22) at line 1: Unknown column 'n_dataset' in 'where clause'

Why?

Best Answer

Because the order of operations with the WHERE clause is applied first before the SELECT operator. So n_dataset doesn't exist yet when the WHERE clause is being applied.

You would need to use COUNT() as a window function (version of MySQL depending, you should update your tags to include the version) to get the results you're looking for.

Or you can create your COUNT() query in a CTE first, then re-join to your table later on.

But interpreting your logic further, it sounds like your actual end goal is to get all exams that don't have any correlating datasets. You can accomplish that a lot simpler with a LEFT JOIN this way:

select distinct exam.id as exam_id, 0 as n_dataset
from exam
left join dataset
    on exam.id = dataset.id
where dataset.id is null