I have two tables:
table1 (id, name, connte)
table2 (id, name, connte)
They are connected through table1.connte and table2.connte. And each of them contains 100 records.
Now if I want to delete a record from table1 with id = 20 and its corresponding children in table2, is it better to do the following:
DELETE d1,d2 FROM table1 d1 INNER JOIN table2 d2 ON d1.connte= d2.connte WHERE d1.id = 20
or the following:
select connte from table1 where id = 20
--Store connte in a variable say aabc--
delete from table2 where connte = aabc -> execute this first
delete from table1 where id = 20 -> execute this second
If there is only one parent and one child for a record that I want to delete (here table1.id =20), then isn't it expensive to do inner join for the whole table?
I am running this query from JAVA (so JDBC), so is it more expensive (performance wise) to run multiple queries or an inner join, for the above mentioned condition?
NOTE: Assuming no referential integrity for the tables. So, I am not using cascade delete.
Generally, we use INNER JOIN when we want to select only rows that match an ON condition. If no rows match the ON condition, then it will not return any results. This can be somewhat stricter than using a LEFT JOIN .
You'll use INNER JOIN when you want to return only records having pair on both sides, and you'll use LEFT JOIN when you need all records from the “left” table, no matter if they have pair in the “right” table or not.
No, they are not necessary.
The biggest difference between an INNER JOIN and an OUTER JOIN is that the inner join will keep only the information from both tables that's related to each other (in the resulting table). An Outer Join, on the other hand, will also keep information that is not related to the other table in the resulting table.
It will probably be faster to do it in one query, rather than two. You are basically trying to do optimizations yourself instead of letting the DBMS do it, and generally DBMS' are really good at this sort of stuff.
Also, you probably won't have to worry about delete performance for tables this small. 100 x 100 rows is still very small, so your DBMS should be able to handle this without a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With