CleanDatabase MySQL optimization

looking at the debug log i noticed that during cleanup there are a lot of “WHERE NOT EXISTS” queries. i think there is a more efficient method, with regard to execution time.

i did some testing. take the following code for example:

Code:
D.E.L.E.T.E FROM actor WHERE NOT EXISTS (S.E.L.E.C.T 1 FROM actor_link WHERE actor_link.actor_id = actor.actor_id) AND NOT EXISTS (S.E.L.E.C.T 1 FROM director_link WHERE director_link.actor_id = actor.actor_id) AND NOT EXISTS (S.E.L.E.C.T 1 FROM writer_link WHERE writer_link.actor_id = actor.actor_id)

i modified “DELETE” to “SELECT *” and ran the query on a table with 12468 rows. the result was 1.9628 sec.

i modified the above code to what i believe is more efficient:

Code:
S.E.L.E.C.T * FROM actor WHERE actor_id not in ( S.E.L.E.C.T actor_id FROM actor_link ) AND actor_id NOT in ( S.E.L.E.C.T actor_id FROM director_link ) AND actor_id NOT in ( S.E.L.E.C.T actor_id FROM writer_link )

and ran the query on the same table. the result was 1.5375 sec.

then i switched back and forth between the two queries 2 more times and got:
NOT EXISTS: 1.7471, 1.8179
NOT IN: 1.3688, 1.3784

averaging the 3 results, i get:
1.84 sec for “NOT EXISTS” methods and 1.43 sec for the “NOT IN” method.

i see five DELETE statements in the debug log. the cumulative time saving could be substantial.

the “NOT IN” method is a suggestion. i am not saying that it is THE most efficient method, but it is better than the existing.

PS> posting SQL code can get you blocked Frown added dots in SELECT & DELETE