SQL Outer Join

Introduction

In SQL, an OUTER JOIN returns rows that match in both tables plus rows from one or both tables that have no corresponding match. There are three main types: LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN. Outer joins allow you to include unmatched data, which is essential when you want to see all elements of one table regardless of matches.

Why Outer Joins Matter

An INNER JOIN returns only matched rows, but sometimes you need to see all records from one side or both. Outer joins let you:
• Identify records without partners (e.g., customers with no orders).
• Produce complete lists with related data when available.
• Simplify reporting by including gaps explicitly.

Sample Data

customers table:

customer_idname
1Alice
2Bob
3Cathy

orders table:

order_idcustomer_idamount
1011230.00
1022150.50
103199.99
1044450.00

LEFT OUTER JOIN

A LEFT OUTER JOIN returns all rows from the left table and matched rows from the right table. Unmatched right table columns show NULL.

SELECT c.customer_id, c.name, o.order_id, o.amount
FROM customers AS c
LEFT JOIN orders AS o
  ON c.customer_id = o.customer_id;  

This ensures every customer appears, even if they have no orders.

customer_idnameorder_idamount
1Alice101230.00
1Alice10399.99
2Bob102150.50
3CathyNULLNULL

RIGHT OUTER JOIN

A RIGHT OUTER JOIN returns all rows from the right table and matched rows from the left table. Unmatched left table columns show NULL.

SELECT c.customer_id, c.name, o.order_id, o.amount
FROM customers AS c
RIGHT JOIN orders AS o
  ON c.customer_id = o.customer_id;  

This guarantees every order appears, even if linked to no existing customer.

customer_idnameorder_idamount
1Alice101230.00
2Bob102150.50
1Alice10399.99
4NULL104450.00

FULL OUTER JOIN

A FULL OUTER JOIN returns all rows when there is a match in either table. Non-matches on either side show NULL for missing values. Not all databases support it directly (MySQL requires UNION of LEFT and RIGHT).

SELECT COALESCE(c.customer_id, o.customer_id) AS customer_id,
       c.name, o.order_id, o.amount
FROM customers AS c
FULL OUTER JOIN orders AS o
  ON c.customer_id = o.customer_id;  

This brings together all customers and all orders in one comprehensive set.

customer_idnameorder_idamount
1Alice101230.00
1Alice10399.99
2Bob102150.50
3CathyNULLNULL
4NULL104450.00

Key Considerations

Always specify a clear ON condition to avoid unintended matches.
Remember that FULL OUTER JOIN can be resource-intensive on large tables.
Use COALESCE to handle NULL keys when combining.

Summary

LEFT, RIGHT, and FULL OUTER JOIN are powerful tools for including unmatched data in your results. Mastering these joins helps beginners explore data gaps and relationships comprehensively.

Previous: SQL INNER JOIN | Next: SQL CREATE Statement

<
>