April 2, 2014 at 9:41 am
I discovered this today and was hoping someone had an explanation. I forgot that a table I was attempting to do a lookup on didn't have the foreign key. I was really surprised when it started returning all rows. I have an example below. I don't even know why it compiles.
Create table #Table1 (
mykey int
)
Create table #BadLookup (
notmykey int
)
insert into #Table1
select 1 union all
select 2 union all
select 3
insert into #BadLookup
select 1
select * from #Table1 where mykey in (select mykey from #BadLookup)
Drop table #Table1
Drop table #BadLookup
April 2, 2014 at 9:46 am
If you used 2-part names for your columns, it should become clear.
select *
from #Table1 t1
where t1.mykey in (select t1.mykey from #BadLookup bl)
It might look weird that the subquery is using a column from the outer query, but it's expected functionality and the base to correlated subqueries.
April 2, 2014 at 10:11 am
Interesting. After a quick search for correlated sub queries I understand why this is expected. Thanks for the help and another tool in my belt.
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply