SQL JOINS
Combine rows from two or more tables based on a related column.
Why JOINs exist
Data is split across multiple tables to avoid repetition (normalization). A customer's name is in the customers table; their orders are in the orders table. JOINs reunite them for queries.
INNER JOIN — only matching rows
Returns only rows where the join condition matches in both tables. Customers with no orders are excluded. Orders with no matching customer are excluded.
LEFT JOIN — all rows from left, matching from right
All customers appear. For customers with no orders, o.product and o.amount are NULL.
RIGHT JOIN — all rows from right, matching from left
All orders appear. Orders with no matching customer (orphaned FKs) still appear with NULL customer name.
FULL OUTER JOIN — all rows from both sides
All rows from both tables. Unmatched rows on either side get NULLs for the other table's columns.
SELF JOIN — a table joined to itself
JOIN types at a glance
| JOIN Type | Returns |
|---|---|
INNER JOIN | Only rows matching on both sides |
LEFT JOIN | All left rows + matching right (NULLs if no match) |
RIGHT JOIN | All right rows + matching left (NULLs if no match) |
FULL OUTER JOIN | All rows from both sides (NULLs where no match) |
CROSS JOIN | Every combination — M × N rows (no ON clause) |
SELF JOIN | Table joined to itself (requires aliases) |
SELECT c.* FROM customers c LEFT JOIN orders o ON c.id = o.customer_id WHERE o.id IS NULL;
This returns customers who have never placed an order — a very common analytics query.