Why joins?#
Data is split across tables to avoid repetition. An order row only has customer_id; the customer's name is in customers. A JOIN combines rows from two tables using a matching column.
JOIN = दो tables को किसी common column (key) के आधार पर जोड़ना - बिल्कुल Excel के XLOOKUP या Power Query के Merge जैसा।
जैसे orders table में सिर्फ customer_id है; customer का नाम जानने के लिए orders को customers table से customer_id पर JOIN करते हैं।
INNER JOIN#
Returns rows that have a match in both tables.
SELECT o.order_id, o.order_date, c.name, c.city
FROM orders AS o
INNER JOIN customers AS c
ON o.customer_id = c.customer_id;
oandcare table aliases - short names that make queries readable.ONsays which columns must match.JOINalone meansINNER JOIN.
LEFT JOIN#
Returns all rows from the left table, plus matching rows from the right table. Where there's no match, the right-side columns are NULL.
Four customers show 0 orders - they signed up but never bought. An INNER JOIN would have hidden them.
Finding unmatched rows (anti-join)#
Great for questions like customers who never ordered, products never sold, students who didn't submit.
Join types at a glance#
| Join | Returns |
|---|---|
INNER JOIN |
only matching rows |
LEFT JOIN |
all left rows + matches (NULL if none) |
RIGHT JOIN |
all right rows + matches (rarely used - swap the tables and use LEFT) |
FULL OUTER JOIN |
all rows from both sides (SQLite 3.39+, PostgreSQL, SQL Server; not MySQL) |
CROSS JOIN |
every combination of rows (e.g. all products × all months) |
Joining three or more tables#
Revenue needs order_items (quantity, discount), products (price) and orders (status, date):
Top customers by revenue#
Watch the grain. orders has one row per order; order_items has one row per product in an order. After joining them, an order with 3 items appears 3 times - so COUNT(*) counts items, not orders. That's why we used COUNT(DISTINCT o.order_id) above.
Self join#
Join a table to itself using two aliases - e.g. employees and their managers:
UNION - stacking results#
JOIN adds columns; UNION adds rows (like Power Query's Append). Both queries need the same number of columns:
SELECT name, 'Customer' AS type FROM customers
UNION ALL
SELECT name, 'Employee' FROM employees;
UNION removes duplicates; UNION ALL keeps them (and is faster).
Summary#
- JOINs combine tables on matching key columns:
FROM a JOIN b ON a.key = b.key. - INNER JOIN keeps matches only; LEFT JOIN keeps all left rows (NULLs where unmatched).
LEFT JOIN ... WHERE right.key IS NULLfinds unmatched rows.- Chain joins for multi-table questions; use aliases; know each table's grain.
- Self joins relate rows in the same table; UNION stacks query results.