snippetsqlMinor
How to optimize NOT IN statement
Viewed 0 times
statementnotoptimizehow
Problem
Why does
Here's my current index on the table,
SQL Statement,
and Execution Plan,
Is there anyway I can optimize this?
NOT IN performs INDEX SCAN instead of INDEX SEEK? Here's my current index on the table,
CREATE NONCLUSTERED INDEX [idx_dmcasarms_CourseList_cDesc]
ON [dbo].[courselist]
(
[c_desc] ASC,
[c_code] ASC
)SQL Statement,
SELECT c_code CourseCode
FROM courselist
WHERE c_desc = 'BACHELOR OF SCIENCE IN INFORMATION TECHNOLOGY'
GO
SELECT c_code CourseCode
FROM courselist
WHERE c_desc NOT IN ('PRE SCHOOL', 'BASIC EDUCATION', 'SCIENCE HIGH SCHOOL')
GOand Execution Plan,
Is there anyway I can optimize this?
Solution
It performs a scan because it has to find all values not in the one listed.
Imagine looking up in a phone book and finding all last name values that aren't 'Smith'.
Then you'll have to scan the entire book. If you instead had to find only those with the last name value 'Smith', then you could just seek to that section.
As for how to optimize, it would unfortunately be to rework the logic to avoid NOT IN if the scan is too costly to accept.
So if you somehow can change your NOT IN to an IN or = it would be better for the database engine.
Of course this can be impossible at time, and then you'll have to weigh the cost of the query vs. the cost of reworking the logic.
Imagine looking up in a phone book and finding all last name values that aren't 'Smith'.
Then you'll have to scan the entire book. If you instead had to find only those with the last name value 'Smith', then you could just seek to that section.
As for how to optimize, it would unfortunately be to rework the logic to avoid NOT IN if the scan is too costly to accept.
So if you somehow can change your NOT IN to an IN or = it would be better for the database engine.
Of course this can be impossible at time, and then you'll have to weigh the cost of the query vs. the cost of reworking the logic.
Context
StackExchange Database Administrators Q#51945, answer score: 7
Revisions (0)
No revisions yet.