I'm trying to understand how EXISTS
work.
The following query is based on this answer, and it queries for all SalesOrderID
s that have more than 1 record in the table, where at lease one of those records has OrderQty > 1
and ProductID = 777
:
USE AdventureWorks2012;
GO
SELECT SalesOrderID, OrderQty, ProductID
FROM Sales.SalesOrderDetail s
WHERE EXISTS
( SELECT 1
FROM Sales.SalesOrderDetail s2
WHERE s.SalesOrderID = s2.SalesOrderID
GROUP BY SalesOrderID
HAVING COUNT(*) > 1
AND COUNT(CASE WHEN OrderQty > 1 AND ProductID = 777 THEN 1 END) >= 1
);
What I don't understand is this: The sub-query returns a single-columned table filled with the value 1
on each row. So the way I understand it, the WHERE
in the outer query has no real condition to apply, just a bunch of 1
s. Why\\How, then, the outer query returns only part of the Sales.SalesOrderDetail
, and not its entirety?
the inner SELECT 1 ...
will not always return 1.
When inner WHERE/HAVING
condition is not met you will not get 1 returned. Instead there will be nothing, I mean the SQL Server Management Studio (if I recall correctly) will display NO result at all, not even NULL for the inner SELECT 1
thus failing the whole outer WHERE
for that particular row.
Therefore part of your outer query result set will be cut off and the total number of rows returned with EXITS(...)
will be less then if EXISTS(...)
was not present.
What happens in EXISTS is that, it only checks if the record from the outer table satisfies the conditions given in the inner query. That's why we specify "1" unlike IN where we need to specify the individual columns (and data is checked for each and every record).
So, it does not return any bunch of 1's and validates it. As the name implies, it checks only for the existence of the record as per the given condition.
Hope this clarifies.
Note : Always use table alias names for the columns to prevent ambiguity.
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.