In the MySQL documentation for joins, a coworker pointed out this gem to me today:
RIGHT JOIN
works analogously toLEFT JOIN
. To keep code portable across databases, it is recommended that you useLEFT JOIN
instead ofRIGHT 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
?
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.
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.
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.
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."
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With