I have 3 tables, the first one, table1, has as primary key the id column, the second table (table2) has a column table1_id that refer as foreign key to the table1.id, the third table (table3) has, as table2, a column table1_id that refer as foreign key to table1.id.
I have to delete from table1 all the rows where table1.id is not in table2.table1_id and not in table3.table1_id
now i am using this query:
DELETE FROM table1
WHERE table1.id IN (SELECT table1.id
FROM (table2
RIGHT OUTER JOIN table1
ON table2.table1_id = table1.id)
LEFT OUTER JOIN table3
ON table3.table1_id = table1.id
WHERE table2.table1_id IS NULL
AND table3.table1_id IS NULL);
but it is very slow, it takes a lot of time, there are some better approach to this delete statement?
If this can help i can assume that table2 has more data that table3.
The database i am using is Apache Derby.
Thanks for the help.
Assuming you got the obvious covered (indices created for
table1.id,table2.table1_idandtable3.table1_id), you don’t need to perform full outer joins just to test if a key is in another table, you can use subqueries andexists()— ornot exists()in your case.And since you’re only testing for existence, you can use the following pattern: