Search code examples
mysqlsqlquery-optimization

SQL Where in: better use a static array or a select?


I have a MySQL database where i need to delete some entrys of a table father, but there are some FK´s with restrictions between my table father and a table child, for that, i have to delete from the child table and afterwards delete from the father table. There i have:

DELETE FROM child WHERE child.id IN (SELECT id FROM father);

I would like to know, if it would have a performance change (besides the extra select) if i used

DELETE FROM child WHERE child.id IN (1,2,...,n)

Where 1,2...n it´s the same result as 'SELECT id FROM father'.


Solution

  • Faster than either is to use a multi-table DELETE:

    DELETE FROM child
        USING father JOIN child 
            ON child.id = father.id;
    

    Shouldn't it be child.father_id?? No, even that seems wrong??

    This seems closer to your English:

    DELETE FROM child
        USING father JOIN child 
            ON child.father_id = father.id   -- more likely FK
        WHERE father...;   -- picking the Dads in question
    DELETE FROM father
        WHERE father...;   -- picking the Dads in question
    

    ON DELETE CASCADE may be slightly faster.