Reputation: 2548
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?
Upvotes: 2
Views: 214
Reputation: 499
I think these two articles answer your question.
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.
Upvotes: 3
Reputation: 1460
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?
Upvotes: 2