I am working on optimizing one of the SQL Job.
Here I have few places where we have used <> operator. THe same query can be replaced using NOT EXISTS operator. I am just wondering which is better way of doing it.
Sample Query
If(@Email <> (select Email from Members WHERE MemberId = @MemberId))
--Do Something.
--Same thing can be written as
If(NOT EXISTS (SELECT Email FROM Members WHERE MemberId = @MemberId AND Email = @EmailId))
Which is better?
I went through execution plans for both (coundn’t attach as all image hosting is blocked in office).
I can see <> operator has Assert and Stream Aggregate operations extra than NOT EXISTS. Not sure if they are good or bad or no impact.
NOT EXISTS is generally better (although in your case if the table is small and/or indexed properly it may not be the case).
Almost always you should use EXISTS/NOT EXISTS for queries in which you’re trying to find out whether a certain record exists (or does not exist)!
The reasoning behind is that EXISTS (and NOT EXISTS) queries will stop as soon as the condition is fulfilled (or in the case of NOT EXISTS proven false) as opposed to using sub-queries which will continue to scan records through the whole table.