Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should SQL JOINs be placed in particular order for performance reasons?

Let's say I have the following query. If there are no matches when joining t1 and t2, are all of the other joins ignored by MySQL?

Reason I ask is that if not, then I will break up the query and use PHP to piece it together. If there is no performance hit, then I will just put my JOINs in such an order that don't continue once a previous JOIN doesn't make. Thanks

SELECT whatever
FROM t1
INNER JOIN t2 ON t2.t1id=t1.id
INNER JOIN t3 ON t3.t2id=t2.id
INNER JOIN t4 ON t4.t3id=t3.id
INNER JOIN t5 ON t5.t4id=t4.id
INNER JOIN t6 ON t6.t5id=t5.id
INNER JOIN t7 ON t7.t6id=t6.id
INNER JOIN t8 ON t8.t7id=t7.id
INNER JOIN t9 ON t9.t8id=t8.id
WHERE t1.c=123 AND t4.c=321 AND t6.c=222 AND t9.c=222
like image 616
user1032531 Avatar asked Feb 20 '13 15:02

user1032531


People also ask

Does the order of joins matter for performance SQL?

Basically, join order DOES matter because if we can join two tables that will reduce the number of rows needed to be processed by subsequent steps, then our performance will improve.

Does the order of joins affect performance?

Even though the join order has no impact on the final result, it still affects performance. The optimizer will therefore evaluate all possible join order permutations and select the best one. That means that just optimizing a complex statement might become a performance problem.

Does order of join criteria matter?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.


1 Answers

The documentation for MySQL states "The join optimizer calculates the order in which tables should be joined".

This order is determined based on information about the sizes of the tables and other factors, such as the presence of indexes.

You should put the joins in the order that makes the most sense for reading and maintaining the query.

like image 183
Gordon Linoff Avatar answered Sep 22 '22 17:09

Gordon Linoff