LEFT JOIN

Basic SQL
≈ 1 min read

LEFT JOIN preserves the entire left table

LEFT JOIN returns every row from the source on the left. If a matching row exists on the right, its data is added. If there is no match, columns from the right side contain NULL.

SELECT u.id, u.name, o.id AS order_id
FROM users AS u
LEFT JOIN orders AS o ON o.user_id = u.id;

The result contains every user, including users who do not have any orders yet. For those users, order_id is NULL.

LEFT JOIN is often used to find missing relationships

SELECT u.id, u.name
FROM users AS u
LEFT JOIN orders AS o ON o.user_id = u.id
WHERE o.id IS NULL;

Here, the join first preserves every user, and then WHERE keeps only users for whom no order was found on the right.

Table order matters for LEFT JOIN. LEFT literally means: “preserve every row from the source written to the left of JOIN.”