I have a query that uses the IN clause. Here’s a simplified version:
SELECT *
FROM table A
JOIN table B
ON A.ID = B.ID
WHERE B.AnotherColumn IN (SELECT Column FROM tableC WHERE ID = 1)
tableC doesn’t have a Column column, but the query executes just fine with no error message. Can anyone explain why?
This will work if a table in the outer query has a column of that name. This is because column names from the outer query are available to the subquery, and you could be deliberately meaning to select an outer query column in your subquery SELECT list.
For example:
As Damien observes, the safest way to protect yourself from this none-too-obvious “gotcha” is to get into the habit of qualifying your column names in the subquery: