user2962554
user2962554

Reputation: 11

(SQL) Replaced NOT IN with NOT EXISTS and results differ

Trying to fix someone else's code. The NOT IN kills performance. I took it out and replaced with Not Exists and I'm getting different results. The commented out not in is just above my not exists. Anyone see anything stupid I'm doing here?

IF @ProcessComplete = 1
    BEGIN

--      PRINT 'Group-Complete'
    INSERT INTO @ProcessIDTable
    SELECT DISTINCT(ProcessID)
    FROM vPortalInbox
    WHERE  GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%' 
    AND StepOwnerID IS NULL

    --AND ProcessID NOT IN (SELECT ProcessID FROM @ProcessIDTable)

    And  not exists (SELECT ProcessID FROM @ProcessIDTable)

Upvotes: 0

Views: 1146

Answers (2)

Monty Wild
Monty Wild

Reputation: 4001

You could try:

And not exists (
  SELECT ProcessID
  FROM @ProcessIDTable
  WHERE ProcessID = vPortalInbox.ProcessID)

...or possibly even better still: you could try a (left or right) outer join to vPortalInbox on ProcessID, and specify in your WHERE clause that @ProcessIDTable.ProcessID IS NULL:

...
SELECT DISTINCT(ProcessID)
FROM vPortalInbox LEFT OUTER JOIN @ProcessIDTable 
     ON vPortalInbox.ProcessID = @ProcessIDTable.ProcessID 
WHERE  GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%' 
AND StepOwnerID IS NULL AND @ProcessIDTable.ProcessID IS NULL

Upvotes: 2

PankajSays
PankajSays

Reputation: 1045

1 --AND ProcessID NOT IN (SELECT ProcessID FROM @ProcessIDTable)

2 And  not exists (SELECT ProcessID FROM @ProcessIDTable)

The above two statements are not same. The not exist will evaluate to true only when you get no rows from the subquery inside the brackets following the not exists clause. Since you have no conditions for the sub-query following not exists clause, it will never return 0 rows unless the table is empty.

Try using this where clause:

FROM vPortalInbox P1
WHERE  GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%' 
AND StepOwnerID IS NULL

And  not exists (SELECT 1 FROM @ProcessIDTable P2
                 where  P1.ProcessID = P2.ProcessID  )

Upvotes: 0

Related Questions