Explain Codes LogoExplain Codes Logo

When or why would you use a right outer join instead of left?

sql
join
data-integrity
sql-performance
Alex KataevbyAlex Kataev·Oct 1, 2024
TLDR

You'd use a Right Outer Join when the priority lies with retrieving all records from the right table, align them with matching data from the left, and filling non-matching entries with NULL. It's the reverse of a Left Outer Join useful in scenarios where, contextually, the right table logically seems to come first enhancing the query readability.

Example:

SELECT r.*, l.* FROM right_table r RIGHT OUTER JOIN left_table l ON r.id = l.right_table_id; -- Party on r.id, bring your own keys

Every record from the right_table is retrieved, with additional left_table data added when matching id's exist, or a wild NULL appears!

Right over Left? Making Sense of it All

Justification for Right Joins

Right Outer Joins are particularly beneficial in scenarios where the table order reflects the flow of the business process or logical operations under consideration. It helps engineers rightly decipher your thought process and workflow.

As your SQL grows in complexity incorporating multiple joins and intersections, the Right Join comes to the rescue ensuring data completeness and integrity, especially in situations where restructuring your query to a left join reduces readability and obfuscates meaning.

Emphasising Table Relationships with Right Joins

In the vast realm of one-to-many relationships, the valiant Right Join takes centre-stage when we need to emphasize the independent table and display all its records, even in the absence of corresponding entries in the joined table.

Practical Usage and Query Performance

Subqueries vs Right Joins: The Dance-off

Sometimes subqueries and common table expressions (CTEs) can be gracefully retired with the help of Right Joins. They provide a direct route to join a table intersection of multiple others, leading to cleaner, meaner SQL.

Transitioning in Syntax with Right Joins

A Right Join can smoothly facilitate syntax transitions or help map older conventions to newer ones. It's beneficial for developers who are more comfortable with the sight of certain tables on the "right" side of the join.

Fixing those Full Joins

Our friend Right Join can help rectify results from full joins, ensuring all records from the right-side table are included, avoiding unnecessary duplication or exclusion.