← Zurück zum Kurs: SQL and databases from scratch

INNER JOIN and LEFT JOIN

Video folgt in Kürze

A JOIN combines rows from two tables according to a condition that almost always compares a foreign key with the primary key it points to. Instead of querying table by table, you write a single query and the database does the matching. It is the most powerful tool in SQL and the one most practiced in interviews and real work, so it deserves to be taken slowly.

INNER JOIN: only what matches

INNER JOIN (or simply JOIN) returns only the rows that have a match in both tables. The condition goes in ON. To avoid repeating long names, table aliases are used (o for orders, c for customers), and you write alias.column to know which table each piece of data comes from; it is mandatory when the column name exists in both tables, such as customer_id or name.

sql
-- Each order with the name of the customer who placed it
SELECT o.order_id, o.order_date, c.name AS customer
FROM orders AS o
INNER JOIN customers AS c ON c.customer_id = o.customer_id
ORDER BY o.order_id;

-- Total spent per customer (cancelled orders excluded)
SELECT c.name, SUM(oi.quantity * oi.unit_price) AS total_spent
FROM customers c
JOIN orders o       ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY c.customer_id, c.name
ORDER BY total_spent DESC;

The second query chains three tables: each JOIN adds one more, always with its own ON. You can chain as many as you need, but it is wise to do it one at a time, checking the result at each step. We group by c.customer_id and also by c.name: the first guarantees that two customers with the same name are not mixed, and the second lets us show the name. A customer with no orders does not appear, because INNER JOIN keeps only matches.

LEFT JOIN: keep everything from the left

LEFT JOIN returns all rows of the left table (the one after FROM) and, for each, the matches from the right; if there are none, the right-hand columns come out as NULL. It is the way to answer questions of the type who has not done something: customers without orders, products that were never sold. You join with LEFT JOIN and filter with WHERE right_column IS NULL.

sql
-- Customers who never ordered
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;

-- Products that were never sold
SELECT p.product_id, p.name
FROM products p
LEFT JOIN order_items oi ON oi.product_id = p.product_id
WHERE oi.item_id IS NULL;

-- Number of orders per customer, including 0
SELECT c.name, COUNT(o.order_id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY orders DESC, c.name;

When you write a JOIN, think first about the business question and then about the technique. Do you want only the items that are related in both tables? Use INNER JOIN. Do you want all the items of one table, related or not? Use LEFT JOIN from that table. Do you want those with no relation? LEFT JOIN and filter by NULL. Also, a very useful debugging trick: before aggregating, run the JOIN without GROUP BY and look at some rows. That way you will see whether the matching is the expected one and whether any row is being multiplied by mistake.

sql
-- All customers, counting only their delivered orders (condition in ON keeps everyone)
SELECT c.name, COUNT(o.order_id) AS delivered_orders
FROM customers c
LEFT JOIN orders o
       ON o.customer_id = c.customer_id AND o.status = 'delivered'
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →