SQLSQL
IntermediateLesson 6 of 15

JOINs – Combining Tables – SQL

INNER, LEFT, anti-joins, self-joins, and multi-table joins.

Relational data is spread across several tables; JOIN puts it back together via keys. With an INNER JOIN, only rows with a match on both sides remain. Table aliases (k, b) keep queries readable.

SELECT k.name, b.id AS bestellung, b.datum, b.status
FROM kunden k
INNER JOIN bestellungen b ON b.kunde_id = k.id
ORDER BY b.datum;
-- Eva does not appear: she has no order

The LEFT JOIN keeps all rows of the left table; without a match, the right side is NULL. This lets you find "customers without an order" (anti-join) or count zeros too. Important: conditions on the right table belong in ON, otherwise WHERE effectively turns the LEFT JOIN into an INNER JOIN.

-- Customers without an order (anti-join)
SELECT k.name
FROM kunden k
LEFT JOIN bestellungen b ON b.kunde_id = k.id
WHERE b.id IS NULL;                         -- Eva

-- Number of orders per customer, including 0
SELECT k.name, COUNT(b.id) AS bestellungen
FROM kunden k
LEFT JOIN bestellungen b ON b.kunde_id = k.id AND b.status <> 'storniert'
GROUP BY k.id, k.name;

To join across several tables, simply chain the joins. For "all combinations" there is CROSS JOIN, and a self-join joins a table with itself (e.g. employees with their managers, or customers from the same city).

SELECT b.id, k.name, p.name AS produkt, bp.menge, bp.menge * p.preis AS zeilenwert
FROM bestellungen b
JOIN kunden k             ON k.id = b.kunde_id
JOIN bestellpositionen bp ON bp.bestellung_id = b.id
JOIN produkte p           ON p.id = bp.produkt_id
WHERE b.id = 6;

-- Pairs of customers from the same city
SELECT a.name, b.name, a.stadt
FROM kunden a JOIN kunden b ON a.stadt = b.stadt AND a.id < b.id;   -- Ada + Cem (Berlin)
WarningDialect: RIGHT JOIN and FULL OUTER JOIN are supported by PostgreSQL and SQLite (from 3.39). MySQL has no FULL OUTER JOIN – there you combine LEFT JOIN UNION RIGHT JOIN. In practice, you almost always get by with INNER and LEFT.
TipIf rows seem to "multiply", a 1:n join before a SUM is usually to blame – aggregate first in a subquery or CTE and then join the result.