Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to rewrite a NOT IN query to use indexes?

Tags:

sql

sqlite

Sqlite does not support the use of indexes in queries based around a NOT IN clause.

Is it possible to logically rewrite a query like the following in such a way that it will only use the operators listed at the link above?

The query:

Select *
From table
Where table-column not in (
    Select table-column
    From table2);

The operators listed as being able to use an index:

  • column = expression
  • column > expression
  • column >= expression
  • column < expression
  • column <= expression
  • expression = column
  • expression > column
  • expression >= column
  • expression < column
  • expression <= column
  • column IN (expression-list)
  • column IN (subquery)
  • column IS NULL
like image 574
dlanod Avatar asked Feb 14 '23 09:02

dlanod


2 Answers

Use a LEFT JOIN as described in section 6.

SQLFiddle with sample data here. Expand View Execution Plan to confirm that the original query does a table scan, while the LEFT JOIN query uses the index.

like image 198
Bryan Avatar answered Feb 17 '23 09:02

Bryan


Select A.*
From table a
left join table2 b 
 on a.table-column = b.table-column
WHERE b.table-column is null
like image 39
xQbert Avatar answered Feb 17 '23 09:02

xQbert