Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it better not to use inner join?

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.

like image 337
Harke Avatar asked Jun 05 '12 14:06

Harke


People also ask

Why not use inner join?

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 .

When should I use inner 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.

Is inner join necessary?

No, they are not necessary.

When to use inner join and outer join?

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.


1 Answers

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.

like image 84
Oleksi Avatar answered Sep 20 '22 22:09

Oleksi