0
0
PostgreSQLquery~15 mins

LEFT JOIN and RIGHT JOIN in PostgreSQL - Deep Dive

Choose your learning style9 modes available
Overview - LEFT JOIN and RIGHT JOIN
What is it?
LEFT JOIN and RIGHT JOIN are ways to combine rows from two tables based on a related column. LEFT JOIN returns all rows from the left table and matching rows from the right table, filling with NULLs if no match exists. RIGHT JOIN does the opposite: it returns all rows from the right table and matching rows from the left table, filling with NULLs if no match exists. These joins help you see related data even when some matches are missing.
Why it matters
Without LEFT and RIGHT JOINs, you would only see rows where both tables have matching data, missing important information from one side. These joins let you find unmatched records, like customers without orders or products without sales, which is crucial for complete analysis and decision-making.
Where it fits
Before learning LEFT and RIGHT JOINs, you should understand basic SELECT queries and INNER JOINs, which combine only matching rows. After mastering these joins, you can explore FULL OUTER JOINs, CROSS JOINs, and advanced filtering techniques to handle complex data relationships.
Mental Model
Core Idea
LEFT JOIN keeps all rows from the left table and adds matching rows from the right, while RIGHT JOIN keeps all rows from the right table and adds matching rows from the left, filling gaps with NULLs.
Think of it like...
Imagine two lists of friends: one from your school (left) and one from your sports club (right). A LEFT JOIN is like listing all your school friends and adding their sports club info if they have it. A RIGHT JOIN is like listing all sports club friends and adding their school info if available.
Left Table       Right Table
┌───────────┐    ┌───────────┐
│ A │ B    │    │ B │ C    │
├───────────┤    ├───────────┤
│ 1 │ x    │    │ x │ 100  │
│ 2 │ y    │    │ y │ 200  │
│ 3 │ z    │    │ z │ 300  │
└───────────┘    └───────────┘

LEFT JOIN Result:
┌────┬────┬─────┐
│ A  │ B  │ C   │
├────┼────┼─────┤
│ 1  │ x  │ 100 │
│ 2  │ y  │ 200 │
│ 3  │ z  │ 300 │
│ 4  │ w  │ NULL│
└────┴────┴─────┘

RIGHT JOIN Result:
┌────┬────┬─────┐
│ A  │ B  │ C   │
├────┼────┼─────┤
│ 1  │ x  │ 100 │
│ 2  │ y  │ 200 │
│ 3  │ z  │ 300 │
│NULL│ v  │ 400 │
└────┴────┴─────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Basic Table Joins
🤔
Concept: Introduce the idea of combining rows from two tables based on a shared column.
When you have two tables, you often want to see how their data relates. For example, a table of customers and a table of orders. A JOIN combines rows where a key matches, like customer ID. INNER JOIN shows only rows where both tables match.
Result
You get a new table with rows only where the key exists in both tables.
Understanding that JOINs combine related data is the foundation for all more complex joins.
2
FoundationWhat is NULL in Joins?
🤔
Concept: Explain NULL as a placeholder for missing data in join results.
When a join tries to find matching rows but none exist, it fills the missing side with NULL. NULL means 'no data here'. This is important to know because it shows where matches are missing.
Result
Joined tables may have NULLs where no matching row exists.
Recognizing NULLs in join results helps you spot unmatched data and understand the completeness of your query.
3
IntermediateLEFT JOIN: Keep All Left Rows
🤔Before reading on: do you think LEFT JOIN returns only matching rows or all rows from the left table? Commit to your answer.
Concept: LEFT JOIN returns all rows from the left table and matches from the right, filling NULLs when no match.
Imagine you want to list all customers and their orders if any. LEFT JOIN keeps every customer, even those without orders. The order columns will be NULL for customers with no orders.
Result
You get all left table rows, with right table data where available, NULL otherwise.
Knowing LEFT JOIN keeps all left rows helps you find missing matches on the right side.
4
IntermediateRIGHT JOIN: Keep All Right Rows
🤔Before reading on: does RIGHT JOIN keep all rows from the right table or the left? Commit to your answer.
Concept: RIGHT JOIN returns all rows from the right table and matches from the left, filling NULLs when no match.
If you want to list all orders and their customers, even orders without customers, RIGHT JOIN keeps every order. Customer info will be NULL if missing.
Result
You get all right table rows, with left table data where available, NULL otherwise.
Understanding RIGHT JOIN is the mirror of LEFT JOIN, focusing on the right table's completeness.
5
IntermediateComparing LEFT JOIN and RIGHT JOIN
🤔Before reading on: do you think LEFT JOIN and RIGHT JOIN can produce the same results? Commit to your answer.
Concept: LEFT JOIN and RIGHT JOIN are symmetrical; switching table order switches the join type.
LEFT JOIN A to B is the same as RIGHT JOIN B to A. The difference is which table is considered 'left' or 'right'. This affects which rows are all kept.
Result
You see that changing table order changes which rows are preserved.
Knowing the symmetry helps you choose the join type based on which table you want to keep fully.
6
AdvancedHandling NULLs After Joins
🤔Before reading on: do you think NULLs in join results mean missing data or zero/empty values? Commit to your answer.
Concept: NULLs after joins mean no matching row, not zero or empty; this affects filtering and calculations.
When you see NULLs in joined columns, it means no match was found. If you filter with WHERE column = value, you might accidentally exclude these rows. Use WHERE column IS NULL or IS NOT NULL to handle them properly.
Result
You learn to write queries that correctly handle unmatched rows with NULLs.
Understanding NULL semantics prevents common bugs in filtering and aggregation after joins.
7
ExpertPerformance and Execution of LEFT and RIGHT JOINs
🤔Before reading on: do you think LEFT JOIN and RIGHT JOIN have the same performance or does one tend to be faster? Commit to your answer.
Concept: LEFT and RIGHT JOINs are logically symmetrical but query planners may optimize differently based on table size and indexes.
PostgreSQL query planner decides join order and method. Sometimes rewriting RIGHT JOIN as LEFT JOIN by swapping tables helps optimization. Understanding execution plans helps write faster queries.
Result
You can optimize queries by choosing join direction and analyzing execution plans.
Knowing how the database executes joins helps you write efficient queries and avoid slowdowns.
Under the Hood
LEFT JOIN and RIGHT JOIN work by scanning the 'preserved' table (left for LEFT JOIN, right for RIGHT JOIN) and for each row, searching the other table for matching rows. If matches exist, rows are combined; if not, NULLs fill the missing side. Internally, the database uses indexes and join algorithms like nested loops, hash joins, or merge joins to perform this efficiently.
Why designed this way?
These joins were designed to let users see all data from one table while optionally including related data from another. This solves the problem of incomplete matches in relational data. LEFT and RIGHT JOINs provide flexibility depending on which table's completeness is more important. Alternatives like FULL OUTER JOIN exist but are more expensive and less commonly needed.
┌───────────────┐       ┌───────────────┐
│ Left Table    │       │ Right Table   │
│ (preserved)   │       │ (matched)     │
└──────┬────────┘       └──────┬────────┘
       │                       │
       │ For each left row     │
       │ find matching right   │
       │ rows                  │
       │                       │
       ▼                       ▼
┌─────────────────────────────────────┐
│ Result Row: left columns + right columns or NULLs if no match │
└─────────────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does LEFT JOIN only return rows where both tables match? Commit yes or no.
Common Belief:LEFT JOIN returns only rows where both tables have matching keys.
Tap to reveal reality
Reality:LEFT JOIN returns all rows from the left table, even if there is no match in the right table, filling right columns with NULL.
Why it matters:Believing this causes missing important unmatched rows, leading to incomplete data analysis.
Quick: Is RIGHT JOIN just a rare, unnecessary join type? Commit yes or no.
Common Belief:RIGHT JOIN is rarely used and can be ignored in favor of LEFT JOIN.
Tap to reveal reality
Reality:RIGHT JOIN is just LEFT JOIN with table order swapped; it is useful when the right table's completeness matters or for readability.
Why it matters:Ignoring RIGHT JOIN limits query expressiveness and can lead to confusing rewrites.
Quick: Does NULL in join results mean zero or empty value? Commit yes or no.
Common Belief:NULL in join results means zero, empty string, or default value.
Tap to reveal reality
Reality:NULL means no matching row exists; it is different from zero or empty and must be handled explicitly.
Why it matters:Misinterpreting NULL leads to wrong calculations, filters, and data interpretation.
Quick: Can LEFT JOIN and RIGHT JOIN always be swapped without changing results? Commit yes or no.
Common Belief:LEFT JOIN and RIGHT JOIN are always interchangeable by swapping tables.
Tap to reveal reality
Reality:They are interchangeable only if you swap the table order and adjust the query accordingly; otherwise, results differ.
Why it matters:Assuming interchangeability without adjusting queries causes wrong data outputs.
Expert Zone
1
LEFT JOIN and RIGHT JOIN can produce different query plans depending on table size and indexes, affecting performance.
2
Using RIGHT JOIN is less common in practice; many experts prefer LEFT JOIN with swapped tables for clarity and consistency.
3
NULLs introduced by these joins can affect aggregate functions and filtering in subtle ways, requiring careful query design.
When NOT to use
Avoid LEFT or RIGHT JOIN when you need all rows from both tables regardless of matches; use FULL OUTER JOIN instead. For simple matching rows only, use INNER JOIN for better performance.
Production Patterns
In production, LEFT JOIN is often used to find missing related data, like customers without orders. RIGHT JOIN is used less but can simplify queries when the right table is the main focus. Query tuning often involves rewriting RIGHT JOIN as LEFT JOIN for planner optimization.
Connections
FULL OUTER JOIN
Builds-on LEFT and RIGHT JOIN concepts by combining both to keep all rows from both tables.
Understanding LEFT and RIGHT JOIN is essential to grasp FULL OUTER JOIN, which merges their behaviors to show all data.
Null Handling in Programming
Shares the concept of NULL as 'missing' or 'unknown' data that must be handled carefully.
Knowing how NULL works in joins helps understand null safety and error handling in programming languages.
Set Theory
LEFT and RIGHT JOINs relate to set operations where one set is fully included and the other partially matched.
Seeing joins as set operations clarifies why some rows appear with NULLs and how data overlaps.
Common Pitfalls
#1Filtering on right table columns in WHERE clause after LEFT JOIN removes unmatched rows.
Wrong approach:SELECT * FROM customers LEFT JOIN orders ON customers.id = orders.customer_id WHERE orders.amount > 100;
Correct approach:SELECT * FROM customers LEFT JOIN orders ON customers.id = orders.customer_id WHERE orders.amount > 100 OR orders.amount IS NULL;
Root cause:Filtering in WHERE after LEFT JOIN excludes rows with NULLs, losing unmatched left rows.
#2Using RIGHT JOIN without understanding table order leads to confusing queries.
Wrong approach:SELECT * FROM orders RIGHT JOIN customers ON orders.customer_id = customers.id;
Correct approach:SELECT * FROM customers LEFT JOIN orders ON customers.id = orders.customer_id;
Root cause:RIGHT JOIN reverses table order; rewriting as LEFT JOIN improves readability and reduces errors.
#3Assuming NULL means zero or empty causes wrong calculations.
Wrong approach:SELECT SUM(orders.amount) FROM customers LEFT JOIN orders ON customers.id = orders.customer_id WHERE orders.amount = 0;
Correct approach:SELECT SUM(COALESCE(orders.amount, 0)) FROM customers LEFT JOIN orders ON customers.id = orders.customer_id;
Root cause:NULL is not zero; COALESCE replaces NULL with zero for correct aggregation.
Key Takeaways
LEFT JOIN and RIGHT JOIN let you keep all rows from one table while adding matching rows from another, filling gaps with NULLs.
NULLs in join results mean no matching row, not zero or empty, and must be handled carefully in queries.
LEFT JOIN and RIGHT JOIN are symmetrical; choosing which to use depends on which table's rows you want to keep fully.
Filtering on joined columns requires care to avoid accidentally removing unmatched rows with NULLs.
Understanding how these joins work internally helps optimize queries and avoid common mistakes.