Home » Mysql » MySQL – Left Joins are Officially Preferred Over Right Joins?

MySQL – Left Joins are Officially Preferred Over Right Joins?

Posted by: admin November 29, 2017 Leave a comment

Questions:

In the MySQL documentation for joins, a coworker pointed out this gem to me today:

RIGHT JOIN works analogously to LEFT JOIN. To keep code portable across databases, it is recommended that you use LEFT JOIN instead of RIGHT JOIN.

Is anyone able to shed some light on this? This strikes me as probably a remnant of a past age – as in maybe the documentation means to say “To keep code reverse compatible with earlier versions of MySQL…”

Is there a modern RDBMS that doesn’t support RIGHT JOIN? I get that RIGHT JOIN is syntactic sugar over LEFT JOIN, and any RIGHT JOIN can be expressed as a LEFT JOIN, but there are times when readability suffers if you write a query in that direction.

Is this advice still modern and valid? Is there a compelling reason to avoid RIGHT JOIN?

Answers:

There’s at least one SQL engine that does not support RIGHT JOIN: SQLite. Maybe that’s the reason why compatibility was listed as a concern. There may potentially be other SQL engines as well.

Questions:
Answers:

So, a RIGHT and LEFT JOIN perform the same action in typical SQL engines. LEFT JOIN table a to table b returns everything from a that exists in b or not. RIGHT JOIN table a to table b returns everything from b that exists in a or not. Prior to optimizing the query, LEFT and RIGHT keywords only refer to an action to be taken on which table. The MySQL optimizer will always normalize the query and make the JOIN effectively a LEFT JOIN. Thus, writing your query to use LEFT JOIN instead of RIGHT will cost less in the optimizer.

Questions:
Answers:

It’s a sensible convention so it should be preferred unless you want to express something distinct or out of the ordinary to anyone who might read it later, (importantly, including yourself).

Your question is valid, though to answer it completed would require either:

1) a counter-example where a RIGHT JOIN doesn’t operate, or operates with significant differences

-or-

2) proof that no such case:1 exists

These will be hard to come by I think. Your suggestion that the advice may have been deprecated since it’s writing is possible. It may also be due to some wrinkle of MySQL supporting multiple database back-ends. Perhaps one of them is RIGHT JOIN intolerant?