2

I ran into a strange behaviour by a query in SQL Server

I have two tables PrepaidTransactions and BillingData and I am executing the following query

Select * 
from PrepaidTransactions 
where customer_Id in
                  (Select customer_Id 
                   from BillingData 
                   where CommunityId = 10004)

The column customer_Id doesn't belong to table BillingData. Instead of showing error the query is executing and returning all the records from the PrepaidTransactions table

But when I run the following query

Select customer_Id 
from BillingData 
where CommunityId = 10004

it is showing an error

Invalid column name 'customer_Id'.

Can anyone please let me know why the first query is not showing any error?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mourya
  • 2,360
  • 3
  • 18
  • 24

2 Answers2

3

I think these two articles answer your question.

https://connect.microsoft.com/SQLServer/feedback/details/542289/subquery-with-error-does-not-cause-outer-select-to-fail

http://support.microsoft.com/kb/298674

This is expected behavior because your column name is not bound to a table. Therefore, if it can be resolved in the outer table (which in your query's case, it can), then the subquery doesn't fail. If you specify the table BillingData.customer_Id, you will get a failure. The articles say to follow this practice to avoid ambiguity.

MoMo
  • 499
  • 3
  • 12
  • the kb article from the second link states that, `In the case of an unqualified column name, the query optimizer assumes that the query is a correlated subquery` , now i understand what is the exact reason and why one should use fully-qualified column name in a sub-query. – Mourya Mar 15 '14 at 09:08
2

wow! I think that in your first case, customer_Id was being pulled from the outer query. You can test that by doing a table prefix:

Select * from PrepaidTransactions where customer_Id in
(Select PrepaidTransactions.customer_Id from BillingData where CommunityId = 10004)

gets same results, but

Select * from PrepaidTransactions where customer_Id in
(Select BillingData.customer_Id from BillingData where CommunityId = 10004)

I bet that errors?

safetyOtter
  • 1,430
  • 14
  • 26