Alternate to 'Except' in SQL with performance

EetSandhu picture EetSandhu · Mar 12, 2017 · Viewed 7.8k times · Source

I've a table TableA as in MS-Sql

 TrId   Status
 2345   3
  567   3
  567   0
 2345   0
   99   3
  778   0

Scenario is few TrIds have status as 3 as well as 0 , some have 3 only some 0 only. I need to find TrIds with status only 3.
One of the ways to do is :

Select TrnId From TableA Where flgStatus = 3
EXCEPT
Select TrnId From Tablea Where flgStatus = 0

There are over 100 million records and i don't have enough time window for except, any alternative for this would be appreciative.

Answer

Igor picture Igor · Mar 12, 2017

You can use NOT EXISTS

SELECT *
FROM TableA a
WHERE flgStatus = 3
AND NOT EXISTS 
(SELECT TrnId From TableA b Where flgStatus = 0 AND a.TrnId = b.TrnId) 

This generally has better performance than NOT IN. A good alternate would be a join, see @ThomasG' answer.