I have the following query
SELECT COUNT(*)
FROM Table1
WHERE Column1 IN
(SELECT Column1 FROM Table2)
Actually there is no column named Column1 in the Table2.
So if we execute only the sub query
SELECT Column1 FROM Table2
it will throw the error – Invalid column name ‘Column1’.
But if I Execute the full query , I am not getting any error. It is returing the total row count in Table1.
So I would like to know the reason why this query it not giving any error in this case And the way the IN clause works in this scenario.
Within a subquery, you’re allowed to access columns from the outer query. And that’s what’s happening here:
Could also be written as:
Provided that there’s at least one row in
Table2, the subquery will always return theColumn1value fromTable1, and theIN()will be successful.This is one reason I usually recommend using aliases:
will produce an error if there’s no
Column1inTable2– or, if you do referencet1inside the subquery, it’s more obvious that it’s deliberate.