Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subquery not in performance question

I have this slow query

select * from table1 where id NOT IN ( select id from table2 )

Would this be faster by doing something like (not sure if this is possible):

select * from table1 where id not in ( select id from table2 where id = table1.id )

Or:

select * from table1 where table1.id NOT EXIST( select id from table2 where table2.id = table1.id )

Or:

select * from table1
left join table2 on table2.id = table1.id
WHERE table2.id is null

Or do something else? Like break it up into two queries ...

like image 300
Mark Steudel Avatar asked Oct 26 '10 02:10

Mark Steudel


1 Answers

The question is - are the field(s) in the comparison nullable (meaning, can the column value be NULL)?

If they're nullable...

...in MySQL the NOT IN or NOT EXISTS perform better - see this link.

If they are NOT nullable...

... LEFT JOIN / IS NULL performs better - see this link.

like image 200
OMG Ponies Avatar answered Oct 14 '22 12:10

OMG Ponies