In one sentence

Only rows with matches in both tables appear in the results of an INNER JOIN. A LEFT JOIN returns all rows from the table on the left and any matching rows from the table on the right; if there are no records that match, the data for the right table will be returned as NULL.

If you know Python

Joins are like looking up values in a Python dictionary or merging pandas DataFrames, except that the database handles the matching.

customers_by_id = {c['id']: c for c in customers}
for order in orders:
    customer = customers_by_id[order['customer_id']]
    print(f"{customer['name']} ordered {order['product']}")

In SQL, remember we use declarative syntax, so we don’t have to tell it how to JOIN, just what columns to JOIN on.

SELECT c.name, o.product, o.amount
FROM orders o
JOIN customers c ON o.customer_id = c.id

The usual mistake

A plain JOIN is an INNER JOIN. So if there is a customer with no orders, we would not see them in this query. Similarly, if there was an order without a customer associated, it would not be returned by an INNER JOIN.

If you want to find customers who have never placed an order, an INNER JOIN would exclude them entirely since there is nothing to match on. This is where the LEFT JOIN (also called LEFT OUTER JOIN) comes in.

SELECT c.name, o.product
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id

This query returns every record in the customer table, even those that have not ordered. For customers without orders, the o.product column will show NULL.

Example

Find customers with no orders. This is the LEFT JOIN pattern in action, and it is one you will reach for often.

SELECT c.name, c.email
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
WHERE o.id IS NULL

A customer order summary showing the number of orders and total spent for each customer, including those who haven’t ordered:

SELECT c.name,
       COUNT(o.id) AS order_count,
       SUM(o.amount) AS total_spent
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
GROUP BY c.id, c.name
ORDER BY total_spent DESC

Between INNER JOIN and LEFT JOIN, you will cover the vast majority of your use cases.

Go deeper

JOINs Explained for Python Developers, post 12 of SQL for Python Developers: why data lives in separate tables, primary and foreign keys, table aliases, and the join mistake that returns millions of rows.