Why does this NOT IN query work as intended, but not this NOT EXISTS query?

98 views Asked by At

Working (NOT IN) retrieves 3 rows:

select DISTINCT d.* from Device d , Company c3
WHERE d.deviceid NOT IN
(
    Select d1.deviceid from Device d1, Clone x1 
    WHERE  d1.deviceid =  x1.deviceID 
    AND  
    (
        x1.XPath = 'hi' 
        OR x1.XPath = 'bye' 
    )
    AND 
    ( 
        EXISTS ( select * from (SELECT * FROM [dbo].[Split] ('T130SF0W2050', ',')) as s 
        WHERE x1.Value like '%' + s.items + '%' )
    ) 
)  
AND  
d.companyid = c3.companyid and c3.companynumber in (SELECT * FROM [dbo].[Split] ('00223200', ','))

Not Working(not exists):

select DISTINCT d.* from Device d , Company c3
WHERE  NOT EXISTS
(Select * from Device d1, Clone x1 
    WHERE  d1.deviceid =  x1.deviceID 
    AND  
    (
        x1.XPath = 'hi' 
        OR x1.XPath = 'bye' 
    )
    AND 
    ( 
        EXISTS ( select * from (SELECT * FROM [dbo].[Split] ('T130SF0W2050', ',')) as s 
        WHERE x1.Value like '%' + s.items + '%' )
    )

)  
AND  
d.companyid = c3.companyid and c3.companynumber in (SELECT * FROM [dbo].[Split] ('00223200', ','))

I'm unsure I'm using the exists syntax correct, what should I select from the subquery? I've tried a few different combinations. It won't run if I put WHERE d.deviceid NOT EXISTS

Solution (thanks to Nikola):

add AND d1.deviceid = d.deviceid inside the Exists subquery.

1

There are 1 answers

0
Mark Brown On

The difference is that the NOT IN query returns devices that match the company and don't match the inner query specification.

For the NOT EXIST query to work as written (where "work as written" refers to returning the same result as the top query), there can't be any devices that exist matching the inner query. If any devices match the inner query at all, the query won't return any results.