Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Left Joins are Officially Preferred Over Right Joins?

Tags:

mysql

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?

like image 966
MightyE Avatar asked Jul 11 '12 18:07

MightyE


People also ask

IS LEFT join better than right join?

The most substantial difference between the left and right outer join lies in the unmatched records that are obtained besides matched records. The left join takes all matching records and unmatched records of the left table while the right join takes all matching records and unmatched records of the right table.

Are left join and right join the same?

LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table. RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table. FULL JOIN: combines the results of both left and right outer joins.

Is Right join ever used?

When to Use RIGHT JOIN. The RIGHT OUTER JOIN is used when you want to join records from tables, and you want to return all the rows from one table and show the other tables columns if there is a match else return NULL values.

Why is right join rarely ever used?

Wikipedia states: "In practice, explicit right outer joins are rarely used, since they can always be replaced with left outer joins and provide no additional functionality."


2 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.

like image 124
Jacob Avatar answered Nov 09 '22 23:11

Jacob


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.

like image 45
EMM Avatar answered Nov 10 '22 00:11

EMM