SQL Insights

Use Equality Versus Inequality

You can't always use an equality predicate (e.g., =, IN, EXISTS) in the WHERE clause. However, if possible, try to do so, because with inequality (e.g., <>, NOT IN, NOT EXISTS, etc.), SQL will generally perform a scan rather than a seek.

For example, depending on the data distribution, SQL chooses an index seek for the second statement, even though these two statements return the same number of rows. Granted, the performance difference isn't mind-blowing.

/*
* Inequality
*/
SELECT Id
FROM dbo.MagicNumbers
WHERE Number3 NOT IN ( 1, 2, 3, 4, 5, 6, 7 );
/*
* Equality
*/
SELECT Id
FROM dbo.MagicNumbers
WHERE Number3 IN ( 9, 8, 7 );

Inequality