Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is too many Left Joins a code smell?

If you have for example > 5 left joins in a query is that a code smell that there is ...

  • something wrong with your design?
  • you're doing too much in one query?
  • you're database is too normalized?
like image 730
Ryu Avatar asked Apr 27 '09 14:04

Ryu


People also ask

How many left joins can you have?

Can you LEFT JOIN three tables in SQL? Yes, indeed! You can use multiple LEFT JOINs in one query if needed for your analysis.

Is inner join faster than LEFT JOIN?

However, if you change the matching key in the join query from Name to ID and if there are a large number of rows in the table, then you will find that the inner join will be faster than the left outer join.

When to use left join vs 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.


2 Answers

It's a perfectly legitimate solution for some designs.

Say you have a hierarchy of one-to-many relations like Customer - Order - Basket - Item - Price, etc., which can be unfilled on any level: a Customer may have no Orders, an Order can have no Baskets, etc.

In this case you issue something like:

SELECT  * FROM    Customer c LEFT OUTER JOIN         Order o ON      o.CustomerID = c.ID LEFT OUTER JOIN         Basket b ON      b.OrderID = c.ID … 

Note that it may be inefficient in some cases, and may be replaced with EXISTS or NOT EXISTS (if you only want to figure out that the corresponding records exist or do not exist in other tables).

See this article in my blog for performance details:

  • Finding incomplete orders - how to benefit from replacing LEFT JOIN's with NOT EXISTS
like image 169
Quassnoi Avatar answered Oct 03 '22 00:10

Quassnoi


In the sense that it's something you could/should investigate I'd say yes. It's likely you can get better utility and maintenance by factoring some views out of that.

In the sense that it's "bad code" no, this could quite easily be reasonable especially for larger DBs and modern databases will likely optimise any inefficiencies out.

like image 39
annakata Avatar answered Oct 03 '22 01:10

annakata