简体   繁体   中英

Sql server not parsing Sub-query

I have the below query in SQL server 2012 which is running fine when the whole query is run, but the inner query is not running individually because AdviceRecordID doesn't belong to tblB.

SELECT DISTINCT SubLOBID 
FROM tblA 
WHERE AdviceRecordID 
IN (SELECT AdviceRecordID
    FROM tblB
)

The first case, where the whole query is run, is not considering the WHERE condition at all and returing all the results without any error which is strange for me.

This works as expected and required by the SQL standard. If a subquery references a column that is not available in the tables of the subquery, but is a valid column in the outer query, the value from the outer query's column is used.

So the query:

SELECT DISTINCT SubLOBID 
FROM tblA 
WHERE AdviceRecordID IN (SELECT AdviceRecordID
                         FROM tblB);

Is in fact a co -related subquery and is parsed and executed as:

SELECT DISTINCT SubLOBID 
FROM tblA 
WHERE AdviceRecordID IN (SELECT tblA.AdviceRecordID
                         FROM tblB);

So for each row in tblA the subquery returns the value of tblA.AdviceRecordID once for each row in tblB and compares that to the rules of the IN operator.

That's why the query as a whole is valid, and behaves like no where clause was used as the above is equivalent to:

SELECT DISTINCT SubLOBID 
FROM tblA 
WHERE AdviceRecordID IS NOT NULL;

And if there are no NULL values in the column AdviceRecordID then the WHERE clause is not filtering out anything.

Better to use EXISTS instead of IN clause.

Check the difference:

Difference1

Difference2

SELECT DISTINCT A.SubLOBID 
FROM tblA A
WHERE EXISTS 
(
    SELECT B.AdviceRecordID
    FROM tblB B
    WHERE B.AdviceRecordID=A.AdviceRecordID
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM