Developer Guides, Cheat Sheets & Tools
SQL course - Part 6: COMBINING TABLES
| Part index | Prerequisites | Previous | Next | Full course |
🔗 PART 6 — COMBINING TABLES
28. JOINs, the complete picture
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟡 Intermediate | 40 min | Combine tables with inner, left, full, cross, and self joins · Find rows with no match · Avoid the traps that silently break reports |
[!NOTE] 📌 In plain words: A
JOINsticks two tables together side by side, matching rows using a shared value. It is the single most important skill in SQL, and the one most people half-learn.
🌍 Analogy: You have a guest list (customers) and a stack of RSVP cards (orders). Joining them means laying each RSVP card next to the matching guest’s name. What you do with guests who never RSVP’d — and RSVPs from people not on the list — is exactly what distinguishes the join types.
28.1 🎨 The join types at a glance
customers orders
┌───────┐ ┌───────┐
│ A │ │ │
│ ┌────┼────────┼───┐ │
│ │ B (matches) │ │ │
│ └────┼────────┼───┘ │
│ │ │ C │
└───────┘ └───────┘
INNER JOIN → B only (customers WITH orders)
LEFT JOIN → A + B (ALL customers, orders where they exist)
RIGHT JOIN → B + C (ALL orders, customers where they exist)
FULL JOIN → A + B + C (everything from both sides)
CROSS JOIN → every A × every C (all combinations, no condition)
| Join | Keeps | Real-world question it answers |
|---|---|---|
INNER JOIN |
Only matching rows from both | “Show orders with their customer details” |
LEFT JOIN |
All left rows + matches | “Show all customers, including those who never ordered” |
RIGHT JOIN |
All right rows + matches | Same as LEFT, tables swapped (rarely used) |
FULL OUTER JOIN |
Everything from both sides | “Compare two lists and show what is missing from each” |
CROSS JOIN |
Every combination | “Generate a date × product grid for a report” |
SELF JOIN |
A table joined to itself | “Show each employee with their manager” |
28.2 🎯 INNER JOIN — the workhorse
-- ✅ Works in BOTH
SELECT
o.order_id,
o.order_date,
c.full_name,
c.country
FROM orders AS o
INNER JOIN customers AS c ON c.customer_id = o.customer_id
ORDER BY o.order_date;
[!NOTE] 📌 Reading it out loud: “Take orders. For each one, find the customer whose
customer_idmatches. If there is no match, drop the order.”
The keyword INNER is optional — JOIN alone means INNER JOIN. Write INNER anyway; explicit is better.
Joining three or more tables — just keep chaining:
-- ✅ Works in BOTH: the full picture of one order
SELECT
o.order_id,
o.order_date,
c.full_name AS customer,
p.product_name,
oi.quantity,
oi.unit_price,
CAST(oi.unit_price * oi.quantity * (1 - oi.discount) AS DECIMAL(12,2)) AS line_total
FROM orders AS o
INNER JOIN customers AS c ON c.customer_id = o.customer_id
INNER JOIN order_items AS oi ON oi.order_id = o.order_id
INNER JOIN products AS p ON p.product_id = oi.product_id
WHERE o.order_id = 1002
ORDER BY p.product_name;
Result:
| order_id | order_date | customer | product_name | quantity | unit_price | line_total |
|---|---|---|---|---|---|---|
| 1002 | 2026-01-18 | Mei Chen | MechKey RGB Keyboard | 1 | 129.00 | 129.00 |
| 1002 | 2026-01-18 | Mei Chen | VisionPanel 32 4K | 2 | 749.00 | 1423.10 |
| 1002 | 2026-01-18 | Mei Chen | WorkStation X17 | 1 | 2450.00 | 2205.00 |
[!WARNING] ⚠️ Why
CASTrather thanROUNDhere?ROUNDchanges the value, but not how many decimal places the result is shown with. MultiplyingDECIMAL(10,2) × INT × DECIMAL(4,3)gives a result with many decimal places, soROUND(..., 2)can still display129.00000.CAST(... AS DECIMAL(12,2))also fixes the display to exactly 2 places. UseROUNDfor maths,CASTfor what people see.
[!TIP] 💡 Pro tip on join direction: Write the
ONcondition consistently —ON child.parent_id = parent.parent_id. Pick a direction and never vary it. Consistency makes complex joins scannable at a glance.
28.3 ⬅️ LEFT JOIN — keeping everything on the left
-- ✅ Works in BOTH: EVERY customer, whether or not they ordered
SELECT
c.full_name,
c.country,
o.order_id,
o.order_date
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY c.full_name;
Customers with no orders still appear — with NULL in every orders column.
The most valuable use of LEFT JOIN: finding what is missing.
-- ✅ Works in BOTH: the "anti-join" pattern
-- Which customers have NEVER placed an order?
SELECT c.customer_id, c.full_name, c.email, c.signup_date
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL; -- 🔑 the magic line
[!NOTE] 📌 Why
WHERE o.order_id IS NULLworks: theLEFT JOINgives every customer a row. Customers with orders get real values; customers without get NULLs. Filtering for NULL keeps exactly the non-matching ones. This is called an anti-join, and it answers a huge family of business questions:
- Products never sold
- Orders with no payment recorded
- Employees with no assigned orders
- Users who signed up but never activated
-- Products that have never been ordered
SELECT p.product_id, p.product_name, p.unit_price
FROM products AS p
LEFT JOIN order_items AS oi ON oi.product_id = p.product_id
WHERE oi.product_id IS NULL;
-- Orders with no payment on file — a genuine finance red flag
SELECT o.order_id, o.order_date, o.status
FROM orders AS o
LEFT JOIN payments AS pay ON pay.order_id = o.order_id
WHERE pay.payment_id IS NULL;
28.4 🚨 The LEFT JOIN trap that silently breaks reports
-- ❌ This is secretly an INNER JOIN!
SELECT c.full_name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.status = 'Delivered';
[!WARNING] ⚠️ What went wrong: the
LEFT JOINcorrectly gives non-ordering customers a row full of NULLs. ThenWHERE o.status = 'Delivered'evaluatesNULL = 'Delivered', which isUNKNOWN, and the row is discarded. YourLEFT JOINhas been silently downgraded to anINNER JOIN.
-- ✅ FIX: put the condition in the ON clause instead
SELECT c.full_name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.status = 'Delivered'; -- filters WHICH rows match, not which survive
[!TIP] 💡 The rule: In a
LEFT JOIN, conditions on the right-hand table belong inON. Conditions on the left-hand table belong inWHERE. Get this backwards and your report quietly loses rows — the worst kind of bug, because it produces plausible wrong numbers instead of an error.
28.5 ➡️ RIGHT and FULL OUTER JOIN
-- RIGHT JOIN: all orders, plus customer info where it exists
SELECT c.full_name, o.order_id
FROM customers AS c
RIGHT JOIN orders AS o ON o.customer_id = c.customer_id;
-- Identical result, and far easier to read:
SELECT c.full_name, o.order_id
FROM orders AS o
LEFT JOIN customers AS c ON c.customer_id = o.customer_id;
[!TIP] 💡 Professional convention: never use
RIGHT JOIN. EveryRIGHT JOINcan be rewritten as aLEFT JOINby swapping the tables, and reading a query is much easier when all the joins flow the same direction. Many style guides ban it outright.
-- 🟥 MSSQL: FULL OUTER JOIN is supported
SELECT
c.customer_id,
c.full_name,
o.order_id
FROM customers AS c
FULL OUTER JOIN orders AS o ON o.customer_id = c.customer_id
WHERE c.customer_id IS NULL OR o.order_id IS NULL; -- show only the mismatches
-- 🟦 MySQL has NO FULL OUTER JOIN. Build it from two joins glued together with UNION (Chapter 29):
SELECT c.customer_id, c.full_name, o.order_id
FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id
UNION
SELECT c.customer_id, c.full_name, o.order_id
FROM customers c RIGHT JOIN orders o ON o.customer_id = c.customer_id;
[!IMPORTANT] 🎯 When you actually need
FULL OUTER JOIN: comparing two lists that should match. “Show me every product in our catalogue and every product in the supplier feed, flagging the ones that appear in only one of them.”
28.6 ✖️ CROSS JOIN — every combination
-- ✅ Works in BOTH: 6 categories × 5 suppliers = 30 rows
SELECT c.category_name, s.company_name
FROM categories AS c
CROSS JOIN suppliers AS s;
[!WARNING] ⚠️ A
CROSS JOINon two million-row tables produces a trillion rows and will take your server down. It is almost always an accident — see the next section.
[!IMPORTANT] 🎯 When it is genuinely useful: building a complete grid so your report has no gaps.
-- ✅ Real-world: a sales matrix with a row for EVERY category in EVERY month,
-- showing 0 where there were no sales (instead of missing rows)
SELECT
c.category_name,
m.month_num,
COALESCE(SUM(CASE WHEN o.order_id IS NOT NULL THEN oi.quantity ELSE 0 END), 0) AS units_sold
FROM categories AS c
CROSS JOIN (
SELECT 1 AS month_num UNION ALL SELECT 2 UNION ALL SELECT 3
UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
) AS m
LEFT JOIN products AS p ON p.category_id = c.category_id
LEFT JOIN order_items AS oi ON oi.product_id = p.product_id
LEFT JOIN orders AS o ON o.order_id = oi.order_id
AND MONTH(o.order_date) = m.month_num
AND YEAR(o.order_date) = 2026
GROUP BY c.category_name, m.month_num
ORDER BY c.category_name, m.month_num;
[!TIP] 💡 This “cross join to fill the gaps” pattern is essential for charts. Without it, a month with no sales simply does not appear, and your line chart draws a straight line across the gap instead of dropping to zero.
28.7 🪞 SELF JOIN — a table joined to itself
-- ✅ Works in BOTH: every employee with their manager's name
SELECT
CONCAT(e.first_name, ' ', e.last_name) AS employee,
e.title,
CONCAT(m.first_name, ' ', m.last_name) AS manager,
m.title AS manager_title
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY manager, employee;
[!NOTE] 📌 The
LEFT JOINmatters here. Sarah Mitchell (the CEO) hasmanager_id = NULL. With anINNER JOINshe would vanish from the organization chart entirely.
-- ✅ Find pairs: customers in the same city
SELECT
a.full_name AS customer_a,
b.full_name AS customer_b,
a.city
FROM customers AS a
INNER JOIN customers AS b
ON b.city = a.city
AND b.customer_id > a.customer_id -- 🔑 avoids self-pairs AND mirror duplicates
ORDER BY a.city;
[!TIP] 💡 The
b.customer_id > a.customer_idtrick. Without it you get every customer paired with themselves, plus both (A,B) and (B,A). The greater-than comparison gives you each unordered pair exactly once. Memorize this; it appears in every “find pairs” problem.
-- ✅ Real-world: find products priced within 5% of each other (possible duplicates)
SELECT
p1.product_name AS product_1,
p2.product_name AS product_2,
p1.unit_price, p2.unit_price
FROM products p1
JOIN products p2
ON p2.product_id > p1.product_id
AND p2.category_id = p1.category_id
AND ABS(p1.unit_price - p2.unit_price) / p1.unit_price < 0.05;
28.8 💥 The accidental CROSS JOIN and row multiplication
Mistake 1 — forgetting the ON clause:
-- ❌ 12 customers × 23 orders = 276 nonsense rows
SELECT c.full_name, o.order_id FROM customers c, orders o;
-- ✅ Always use explicit JOIN syntax, which forces you to write ON
SELECT c.full_name, o.order_id
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;
[!TIP] 💡 This is why the old comma-join syntax (
FROM a, b WHERE ...) is banned in modern style guides. ExplicitJOIN ... ONmakes the missing condition a syntax error instead of a silent disaster.
Mistake 2 — fan-out: rows multiplying when you join two “many” tables at once:
-- ❌ WRONG: revenue is multiplied by the number of payments per order
SELECT
o.order_id,
SUM(oi.unit_price * oi.quantity) AS revenue, -- inflated!
SUM(pay.amount) AS paid -- also inflated!
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN payments pay ON pay.order_id = o.order_id
GROUP BY o.order_id;
[!WARNING] ⚠️ What happened: order 1002 has 3 items and 1 payment → 3 rows. If it had 3 items and 2 payments → 6 rows. Every item is counted twice and every payment three times. Your revenue report is now wrong, and it looks plausible.
-- ✅ FIX: aggregate each side separately, then join the results
SELECT
o.order_id,
items.revenue,
pays.paid
FROM orders o
LEFT JOIN (
SELECT order_id, SUM(unit_price * quantity * (1 - discount)) AS revenue
FROM order_items GROUP BY order_id
) AS items ON items.order_id = o.order_id
LEFT JOIN (
SELECT order_id, SUM(amount) AS paid
FROM payments WHERE status = 'Captured' GROUP BY order_id
) AS pays ON pays.order_id = o.order_id;
[!TIP] 💡 The rule: never join two separate one-to-many children in the same query and aggregate. First total up each “many” table to one row per order, then join those totals. This single insight prevents more wrong reports than any other in this guide.
28.9 ⚙️ How joins are executed (and why it matters)
Behind the scenes, the database chooses one of three ways to match rows. You never write these yourself — but the names appear when a join is slow (Chapter 47):
| Method | How it works | Best when | Warning sign |
|---|---|---|---|
| Nested Loops | For each row on the left, look up its matches on the right | One side is small, and the join column has an index | Slow if both sides are large |
| Hash Join | Build a quick lookup list from the smaller table, then check every row of the larger one against it | Both sides are large and there is no useful index | Uses lots of memory; may overflow onto slow disk |
| Merge Join | Walk through both tables side by side, already in the same sorted order | Both sides are already sorted (indexed) | Needs an extra sort if they are not |
[!TIP] 💡 What you control: you cannot choose the algorithm (and should not try), but you strongly influence it by indexing your join columns. A foreign key column with no index is the number-one cause of slow joins in real systems. MySQL creates an index on FK columns automatically; MSSQL does not — you must create it yourself.
-- ✅ 🟥 MSSQL: index every foreign key column. Do this on day one.
-- (MySQL/InnoDB created these indexes for you automatically.)
CREATE INDEX ix_orders_customer_id ON orders(customer_id);
CREATE INDEX ix_orders_employee_id ON orders(employee_id);
CREATE INDEX ix_order_items_product ON order_items(product_id);
CREATE INDEX ix_products_category_id ON products(category_id);
CREATE INDEX ix_payments_order_id ON payments(order_id);
28.10 🧪 Try it yourself
- List every order with its customer name, sales rep name, and item count.
- Find every product that has never been sold.
- Find every customer who has ordered but never had a captured payment.
- Build the org chart: every employee with their manager, including the CEO.
- Deliberately write the
LEFT JOIN+WHEREtrap, observe the row count drop, then fix it by moving the condition intoON. - Write the fan-out mistake from 28.8 and prove the revenue is inflated by comparing against the correct version.
🧭 In practice — JOINs
How to use it. Write
FROM a JOIN b ON b.key = a.key.INNER JOINkeeps only matching pairs;LEFT JOINkeeps every row from the left side and fills the right withNULLwhen there is no match. Expected result: one result set combining both tables — and a row count you should always sanity-check, because joins can multiply rows.When to use it. Whenever the answer needs facts from more than one table — which, in a properly normalised database, is almost every interesting question.
Where to use it. Everywhere. Scenario: “which customers have never ordered?” is a
LEFT JOINfromcustomerstoorderswithWHERE o.order_id IS NULL. That pattern — outer join, then test forNULL— answers every “things without a matching thing” question you will ever be asked.When not to use it. Do not put a condition on the right table of a
LEFT JOINin theWHEREclause: it silently turns the outer join back into an inner one, becauseNULLfails the test. Put it in theONclause instead. And never write a join with noONcondition unless you genuinely want aCROSS JOIN— 12 customers by 18 products is 216 rows, and on real tables it is how you accidentally generate billions.Best practices. Always qualify columns with table aliases (
o.order_id,c.full_name); unqualified columns become ambiguous the moment a second table has the same column name. Index your foreign-key columns — an unindexed FK makes both joins and parent deletes scan the child table. If a join suddenly produces duplicates, fix the join rather than addingDISTINCT: the duplicates mean one row matched many, which usually means the total you are about to report is wrong.
29. Set operators: UNION, INTERSECT, EXCEPT
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟡 Intermediate | 15 min | Stack results with UNION · Find rows in both lists, or in only one · Compare two tables for differences |
[!NOTE] 📌 In plain words: Joins glue tables together side by side (more columns). Set operators stack result sets on top of each other (more rows).
🌍 Analogy: A join is taping two sheets of paper edge to edge to make a wider page. A union is stacking two sheets in the same pile.
29.1 📚 The rules every set operator obeys
- Every query must have the same number of columns.
- Matching columns must have compatible data types (numbers with numbers, text with text).
- The first query’s column names become the result’s column names.
ORDER BYappears only once, at the very end.
29.2 ➕ UNION and UNION ALL
-- ✅ Works in BOTH: UNION removes duplicates
SELECT city FROM customers
UNION
SELECT shipping_city FROM orders
ORDER BY city;
-- ✅ UNION ALL keeps everything, including duplicates
SELECT city FROM customers
UNION ALL
SELECT shipping_city FROM orders;
UNION |
UNION ALL |
|
|---|---|---|
| Removes duplicates | ✅ Yes | ❌ No |
| Speed | 🐢 Slower (it must find and remove duplicates) | 🚀 Fast |
| Use when | You genuinely need distinct rows | You know there are no duplicates, or you want them |
[!TIP] 💡 Default to
UNION ALL. Most of the time you know the two sets cannot overlap — for example, combining this year’s orders table with last year’s archive. Using plainUNIONforces an expensive hunt for duplicates for no benefit. Only reach forUNIONwhen duplicates are genuinely possible and unwanted.
A real-world use: combining live and archived data.
-- ✅ Works in BOTH (orders_archive is the table created in Chapter 12.3)
SELECT order_id, customer_id, order_date, status, 'live' AS source
FROM orders
WHERE order_date >= '2026-01-01'
UNION ALL
SELECT order_id, customer_id, order_date, status, 'archive' AS source
FROM orders_archive
WHERE order_date < '2026-01-01'
ORDER BY order_date DESC;
[!TIP] 💡 Note the literal
'live'/'archive'column. Tagging each branch tells you which source a row came from — invaluable when debugging a union that returns unexpected rows.
Another real use: building a unified contact list.
SELECT full_name AS name, email, 'Customer' AS person_type FROM customers
UNION ALL
SELECT CONCAT(first_name,' ',last_name),
CONCAT(LOWER(first_name),'.',LOWER(last_name),'@shopdb.com'),
'Employee'
FROM employees
ORDER BY person_type, name;
29.3 ∩ INTERSECT — rows in both
-- 🟥 MSSQL: supported natively
SELECT city FROM customers
INTERSECT
SELECT shipping_city FROM orders;
-- 🟦 MySQL 8.0.31+: INTERSECT is supported
-- Older MySQL: imitate it with an inner join or IN
SELECT DISTINCT c.city
FROM customers c
WHERE c.city IN (SELECT shipping_city FROM orders);
29.4 ➖ EXCEPT / MINUS — rows in the first but not the second
-- 🟥 MSSQL: EXCEPT
-- Which customer cities have never been used as a shipping city?
SELECT city FROM customers
EXCEPT
SELECT shipping_city FROM orders;
-- 🟦 MySQL 8.0.31+: EXCEPT is supported
-- Older MySQL: imitate it with NOT EXISTS
SELECT DISTINCT c.city
FROM customers c
WHERE c.city IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.shipping_city = c.city);
[!TIP] 💡
EXCEPTis a fantastic data-comparison tool. To check whether two tables hold identical data, runEXCEPTin both directions. If both return zero rows, the tables contain the same distinct rows. Duplicate counts require a separate grouped-count comparison:-- ✅ Works in BOTH (MySQL 8.0.31+) — products_backup_2026_09 is the copy made in Chapter 8.4 SELECT * FROM products EXCEPT SELECT * FROM products_backup_2026_09; -- in A not B SELECT * FROM products_backup_2026_09 EXCEPT SELECT * FROM products; -- in B not AThis is how experienced engineers check, in 10 seconds, that data was copied correctly.
29.5 🔀 Support and precedence
| Operator | 🟥 MSSQL | 🟦 MySQL |
|---|---|---|
UNION |
✅ | ✅ |
UNION ALL |
✅ | ✅ |
INTERSECT |
✅ | ✅ 8.0.31+ |
EXCEPT |
✅ | ✅ 8.0.31+ (called EXCEPT, not MINUS) |
[!WARNING] ⚠️ Order of evaluation: SQL works out
INTERSECTbeforeUNIONandEXCEPT. When mixing them, use parentheses to make your intent explicit and unambiguous.
[!WARNING] ⚠️
ORDER BYgoes at the very end and applies to the whole result, not to an individual branch. If you need to limit one branch, wrap that branch in a subquery insideFROM(a derived table, Chapter 30).
-- 🟥 MSSQL: limiting inside a branch
SELECT * FROM (
SELECT TOP 5 product_name, unit_price FROM products ORDER BY unit_price DESC
) AS expensive
UNION ALL
SELECT * FROM (
SELECT TOP 5 product_name, unit_price FROM products ORDER BY unit_price ASC
) AS cheap;
-- 🟦 MySQL: the same, with LIMIT inside each branch
SELECT * FROM (
SELECT product_name, unit_price FROM products ORDER BY unit_price DESC LIMIT 5
) AS expensive
UNION ALL
SELECT * FROM (
SELECT product_name, unit_price FROM products ORDER BY unit_price ASC LIMIT 5
) AS cheap;
29.6 🧪 Try it yourself
- Build one list of every city that appears either as a customer city or a shipping city.
- Find the cities that appear in both.
- Find customer cities that have never been shipped to.
- Create a unified “people” list of customers and employees with a type column.
- Verify that
productsand a backup copy contain identical data usingEXCEPTboth ways.
🧭 In practice — set operators
How to use it. Stack two result sets with
UNION(removes duplicates) orUNION ALL(keeps everything).INTERSECTreturns rows in both;EXCEPTreturns rows in the first but not the second. All require the same number of columns, in the same order, with compatible types. Expected result: rows combined vertically, as opposed to a join’s horizontal combination.When to use it. When the same shape of data lives in two places — current and archived orders, two regional tables, this year’s and last year’s extracts.
Where to use it. Reporting across partitioned or archived data, and reconciliation. Scenario:
EXCEPTbetween a source extract and its loaded copy shows exactly which rows failed to load — a two-line data-quality check that would otherwise be a script.When not to use it. Do not use
UNIONwhen you meanUNION ALL.UNIONperforms a sort and deduplicate over the whole combined set, which is expensive and, worse, silently removes legitimate duplicate rows — two customers who genuinely share a city collapse into one. UseUNION ALLunless you specifically want deduplication. Also note MySQL 8.0 addedINTERSECTandEXCEPTonly in 8.0.31.Best practices. Default to
UNION ALLand reach forUNIONdeliberately. Name your columns in the firstSELECT— those names become the result’s column names and the others are ignored, which surprises people. Put a singleORDER BYat the very end; it applies to the combined result, not to each branch.
30. Subqueries and EXISTS
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟡 Intermediate | 30 min | Put a query inside a query · Check whether related rows exist · Build step-by-step calculations inside FROM |
[!NOTE] 📌 In plain words: A subquery is a query inside another query. The inner one runs first (conceptually) and its result feeds the outer one.
🌍 Analogy: “Give me every product that costs more than the average.” You cannot answer that in one step — you must first work out the average (inner query), then compare (outer query). A subquery is that two-step thought written as one statement.
30.1 🔢 Scalar subqueries — returning one single value
-- ✅ Works in BOTH: products priced above the overall average
SELECT product_name, unit_price
FROM products
WHERE unit_price > (SELECT AVG(unit_price) FROM products)
ORDER BY unit_price DESC;
-- A scalar subquery in the SELECT list
SELECT
product_name,
unit_price,
(SELECT AVG(unit_price) FROM products) AS catalog_avg,
ROUND(unit_price - (SELECT AVG(unit_price) FROM products), 2) AS diff_from_avg
FROM products
ORDER BY diff_from_avg DESC;
[!WARNING] ⚠️ A scalar subquery returns one column and at most one row. Zero rows produce
NULL; more than one row raises an error: you get “Subquery returned more than 1 value” (MSSQL) or “Subquery returns more than 1 row” (MySQL).
30.2 📋 Multi-row subqueries: IN, ANY, ALL
-- ✅ Works in BOTH
-- Customers who have placed at least one order
SELECT full_name FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);
-- Products more expensive than EVERY product in category 4
SELECT product_name, unit_price FROM products
WHERE unit_price > ALL (SELECT unit_price FROM products WHERE category_id = 4);
-- Products more expensive than AT LEAST ONE product in category 1
SELECT product_name, unit_price FROM products
WHERE unit_price > ANY (SELECT unit_price FROM products WHERE category_id = 1);
| Operator | Meaning |
|---|---|
IN (…) |
Matches any value in the set |
> ALL (…) |
Greater than the maximum of the set |
< ALL (…) |
Less than the minimum of the set |
> ANY (…) |
Greater than the minimum (i.e. at least one) |
= ANY (…) |
Identical to IN |
[!WARNING] ⚠️ Remember the
NOT IN+ NULL trap from Chapter 14.NOT INwith a subquery that can return NULL silently returns zero rows. UseNOT EXISTS.
30.3 🔗 Correlated subqueries — the inner query depends on the outer
-- ✅ Works in BOTH: each product compared to ITS OWN category's average
SELECT
p.product_name,
p.unit_price,
p.category_id,
(SELECT AVG(p2.unit_price)
FROM products p2
WHERE p2.category_id = p.category_id) AS category_avg -- 🔑 references p
FROM products AS p
WHERE p.unit_price > (
SELECT AVG(p2.unit_price)
FROM products p2
WHERE p2.category_id = p.category_id
)
ORDER BY p.category_id;
[!NOTE] 📌 The difference: a plain subquery runs once. A correlated subquery references a column from the outer query (
p.category_id), so conceptually it runs once per outer row. That makes it powerful and potentially slow.
-- ✅ Real-world: each customer with their most recent order date
SELECT
c.full_name,
(SELECT MAX(o.order_date) FROM orders o WHERE o.customer_id = c.customer_id) AS last_order,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count
FROM customers AS c
ORDER BY last_order DESC;
[!TIP] 💡 When there are several correlated subqueries against the same table, rewrite as a
LEFT JOINwithGROUP BY. The version above scansorderstwice per customer; the join version scans it once, total:SELECT c.full_name, MAX(o.order_date) AS last_order, COUNT(o.order_id) AS order_count FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id GROUP BY c.customer_id, c.full_name;
30.4 ✅ EXISTS and NOT EXISTS — the professional’s choice
-- ✅ Works in BOTH: customers who HAVE ordered
SELECT c.full_name
FROM customers AS c
WHERE EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
-- Customers who have NEVER ordered
SELECT c.full_name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
[!NOTE] 📌
EXISTSasks a yes/no question: “Does at least one matching row exist?” It stops looking the instant it finds one — it does not count, collect, or return anything. That early stop is why it is usually the fastest option.
[!TIP] 💡
SELECT 1insideEXISTSis convention, not requirement. The engine ignores the select list entirely;SELECT *,SELECT 1, andSELECT customer_idall produce identical plans.SELECT 1simply signals your intent to the reader.
The three ways to ask “does a related row exist”, compared:
| Approach | NULL-safe | Typical speed | Readability |
|---|---|---|---|
EXISTS / NOT EXISTS |
✅ Always | ⚡ Usually best | ✅ Clear intent |
IN / NOT IN |
⚠️ NOT IN breaks on NULL |
Good for small lists | ✅ Very readable |
LEFT JOIN ... IS NULL |
✅ Safe | Good, but can multiply rows | ⚠️ Needs a comment |
-- Real-world: which products have sold in the last 3 months?
SELECT p.product_name, p.unit_price
FROM products AS p
WHERE EXISTS (
SELECT 1
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
WHERE oi.product_id = p.product_id
AND o.order_date >= '2026-06-01'
);
30.5 🪆 Derived tables — a subquery in the FROM clause
-- ✅ Works in BOTH
SELECT
band.price_band,
COUNT(*) AS product_count
FROM (
SELECT
product_id,
CASE
WHEN unit_price >= 1000 THEN 'Premium'
WHEN unit_price >= 300 THEN 'Mid'
ELSE 'Budget'
END AS price_band
FROM products
) AS band
GROUP BY band.price_band;
[!WARNING] ⚠️ A derived table must have an alias (
AS band). MySQL and MSSQL both refuse it otherwise — MySQL says “Every derived table must have its own alias.”
-- ✅ Real-world: customers who spend above the company-wide average
SELECT
spend.full_name,
spend.total_spend
FROM (
SELECT
c.customer_id,
c.full_name,
SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS total_spend
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 IN ('Delivered','Shipped')
GROUP BY c.customer_id, c.full_name
) AS spend
WHERE spend.total_spend > (
SELECT AVG(t.total)
FROM (
SELECT o.customer_id, SUM(oi.unit_price*oi.quantity*(1-oi.discount)) AS total
FROM orders o JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY o.customer_id
) AS t
)
ORDER BY spend.total_spend DESC;
[!TIP] 💡 That query is correct but hard to read — the same calculation appears twice. This is precisely the problem CTEs solve. See the next chapter.
30.6 ⚡ Subquery performance
| Pattern | Guidance |
|---|---|
Scalar subquery in SELECT that does not use the outer row |
✅ Fine — runs once |
Scalar subquery in SELECT that uses the outer row (correlated) |
⚠️ Runs once per row; consider a join |
IN with a small constant list |
✅ Fine |
IN with a large subquery |
⚠️ Consider EXISTS or a join |
NOT IN on a column that can be NULL |
🚫 Use NOT EXISTS instead |
EXISTS |
✅ Generally the best choice for existence checks |
| Derived table used twice | ⚠️ A CTE names the expression; a temporary table materializes a reusable result. A CTE alone does not guarantee one evaluation |
[!TIP] 💡 Modern optimizers often rewrite subqueries into joins automatically, so the difference is smaller than people often claim. But “often” is not “always” — check the execution plan rather than trusting a rule of thumb. See Chapter 47.
30.7 🧪 Try it yourself
- Find products priced above their own category’s average.
- Find customers who have ordered from more than one category.
- Rewrite “customers who never ordered” three ways:
NOT EXISTS,NOT IN, andLEFT JOIN ... IS NULL. Compare the plans. - Find the single most expensive product in each category using a correlated subquery.
🧭 In practice — subqueries and EXISTS
How to use it. Nest a query inside another: in
WHEREas a filter (IN,EXISTS, a scalar comparison), inFROMas a derived table, or in theSELECTlist as a scalar value.EXISTSasks only whether any matching row exists and stops at the first one. Expected result: a multi-step question answered in one statement.When to use it. When the filter itself depends on a query — “customers who ordered in March”, “products priced above their category average”.
Where to use it. Everyday querying. Scenario:
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)finds customers with no orders. It is usually the clearest way to express “none of these exist”, and it short-circuits rather than building a full list.When not to use it. Never use
NOT INwith a subquery whose column can beNULL: a singleNULLmakes the whole predicate unknown and the query returns no rows at all, silently. UseNOT EXISTS, which isNULL-safe. Avoid a correlated subquery in theSELECTlist over a large result set — it can run once per output row; a join or window function usually does the same work in one pass.Best practices. Prefer
EXISTStoINfor existence checks, and aJOINwhen you actually need columns from the other table. If a subquery is nested more than two deep, rewrite it as a CTE (Chapter 31) — same result, and a reader can follow it top to bottom. Check the execution plan before assuming any of these is faster; the optimiser often rewrites them into the same thing.
31. CTEs and recursive queries
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟡 Intermediate | 30 min | Write readable step-by-step queries with WITH · Walk hierarchies like an org chart · Generate a list of dates for reports |
[!NOTE] 📌 In plain words: A CTE (Common Table Expression) is a named temporary result you define at the top of your query with
WITH, then use like a table. It turns an unreadable nest of subqueries into a readable sequence of steps.
🌍 Analogy: A recipe. Instead of one impossible sentence — “combine the thing you get from beating eggs with the thing you get from sifting flour mixed with the thing from melting butter” — you write numbered steps, each with a name. CTEs are those named steps.
31.1 ✍️ Basic CTE syntax
-- ✅ Works in BOTH (MySQL 8.0+)
WITH customer_spend AS (
SELECT
c.customer_id,
c.full_name,
c.country,
SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS total_spend
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 IN ('Delivered','Shipped')
GROUP BY c.customer_id, c.full_name, c.country
)
SELECT *
FROM customer_spend
WHERE total_spend > (SELECT AVG(total_spend) FROM customer_spend)
ORDER BY total_spend DESC;
[!NOTE] 📌 Compare that to the double-nested version at the end of Chapter 30. Same result, but the aggregation is written once and given a meaningful name. That is the whole value of a CTE.
31.2 🔗 Multiple CTEs — a readable pipeline
-- ✅ Works in BOTH: a genuine business report built in clear stages
WITH order_totals AS (
-- Step 1: what is each order worth?
SELECT
oi.order_id,
SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS order_value
FROM order_items oi
GROUP BY oi.order_id
),
customer_stats AS (
-- Step 2: roll those up per customer
SELECT
c.customer_id,
c.full_name,
c.country,
c.loyalty_tier,
COUNT(o.order_id) AS order_count,
SUM(ot.order_value) AS lifetime_value,
AVG(ot.order_value) AS avg_order_value,
MAX(o.order_date) AS last_order_date
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_totals ot ON ot.order_id = o.order_id
WHERE o.status IN ('Delivered','Shipped')
GROUP BY c.customer_id, c.full_name, c.country, c.loyalty_tier
),
ranked AS (
-- Step 3: classify them
SELECT
cs.*,
CASE
WHEN cs.lifetime_value >= 3000 THEN 'VIP'
WHEN cs.lifetime_value >= 1000 THEN 'Valued'
ELSE 'Standard'
END AS segment
FROM customer_stats cs
)
-- Step 4: the final answer
SELECT
segment,
COUNT(*) AS customers,
ROUND(AVG(lifetime_value),2) AS avg_ltv, -- ltv = lifetime value
ROUND(SUM(lifetime_value),2) AS segment_revenue
FROM ranked
GROUP BY segment
ORDER BY segment_revenue DESC;
[!TIP] 💡 Read that query top to bottom and it explains itself. Written as nested subqueries it would be roughly 40 lines of parentheses that nobody could safely modify. CTEs are mainly a way to make SQL easier to read and to change — and readable SQL is SQL that gets fixed correctly at 2 a.m.
31.3 🔁 Recursive CTEs — querying hierarchies
This is the feature that makes CTEs genuinely irreplaceable. A recursive query uses its own results to find the next level, step by step, until nothing new turns up. That lets it walk any tree of parent–child links: an organization chart, categories inside categories, folders inside folders, parts inside products.
-- ✅ Works in BOTH (MySQL 8.0+ needs the RECURSIVE keyword)
-- 🟥 MSSQL
WITH org_chart AS (
-- ⚓ ANCHOR: the starting point (the CEO, who has no manager)
SELECT
employee_id,
first_name,
last_name,
title,
manager_id,
0 AS level,
CAST(first_name + ' ' + last_name AS VARCHAR(500)) AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- 🔁 RECURSIVE MEMBER: everyone who reports to someone already found
SELECT
e.employee_id,
e.first_name,
e.last_name,
e.title,
e.manager_id,
oc.level + 1,
CAST(oc.path + ' > ' + e.first_name + ' ' + e.last_name AS VARCHAR(500))
FROM employees e
INNER JOIN org_chart oc ON oc.employee_id = e.manager_id
)
SELECT
REPLICATE(' ', level) + first_name + ' ' + last_name AS org_tree,
title,
level,
path
FROM org_chart
ORDER BY path;
-- 🟦 MySQL 8.0+
WITH RECURSIVE org_chart AS (
SELECT
employee_id, first_name, last_name, title, manager_id,
0 AS level,
CAST(CONCAT(first_name, ' ', last_name) AS CHAR(500)) AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT
e.employee_id, e.first_name, e.last_name, e.title, e.manager_id,
oc.level + 1,
CAST(CONCAT(oc.path, ' > ', e.first_name, ' ', e.last_name) AS CHAR(500))
FROM employees e
INNER JOIN org_chart oc ON oc.employee_id = e.manager_id
)
SELECT
CONCAT(REPEAT(' ', level), first_name, ' ', last_name) AS org_tree,
title, level, path
FROM org_chart
ORDER BY path;
Result:
| org_tree | title | level |
|---|---|---|
| Sarah Mitchell | Chief Executive Officer | 0 |
| Amara Nwosu | Support Lead | 1 |
| Marco Rossi | Support Agent | 2 |
| David Okafor | Sales Director | 1 |
| Priya Raman | Senior Sales Executive | 2 |
| Tom Becker | Sales Executive | 2 |
| … |
The anatomy of every recursive CTE:
WITH [RECURSIVE] cte_name AS (
⚓ ANCHOR QUERY ← where to start. Runs ONCE. Does not refer to itself.
UNION ALL
🔁 RECURSIVE QUERY ← joins back to cte_name. Runs repeatedly
until it returns zero new rows.
)
SELECT ... FROM cte_name;
31.4 🔢 Generating sequences with recursion
-- ✅ Generate every date in a range — essential for gap-free reports
-- 🟥 MSSQL
WITH date_series AS (
SELECT CAST('2026-01-01' AS DATE) AS d
UNION ALL
SELECT DATEADD(DAY, 1, d) FROM date_series WHERE d < '2026-12-31'
)
SELECT d FROM date_series
OPTION (MAXRECURSION 400); -- default limit is 100!
-- 🟦 MySQL 8.0+
WITH RECURSIVE date_series AS (
SELECT DATE('2026-01-01') AS d
UNION ALL
SELECT d + INTERVAL 1 DAY FROM date_series WHERE d < '2026-12-31'
)
SELECT d FROM date_series;
-- Adjust cte_max_recursion_depth if you exceed 1000
-- 🟦 MySQL — real-world use: daily sales with ZERO for days that had none
WITH RECURSIVE date_series AS (
SELECT DATE('2026-01-01') AS d
UNION ALL
SELECT d + INTERVAL 1 DAY FROM date_series WHERE d < '2026-08-31'
)
SELECT
ds.d AS sales_date,
COALESCE(SUM(oi.unit_price * oi.quantity * (1 - oi.discount)), 0) AS revenue
FROM date_series ds
LEFT JOIN orders o ON o.order_date = ds.d AND o.status IN ('Delivered','Shipped')
LEFT JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY ds.d
ORDER BY ds.d;
[!TIP] 💡 Without the date series, days with no sales simply do not appear and your chart draws a misleading straight line between two distant points. This pattern is used in virtually every real dashboard.
31.5 ⚠️ Recursion safety
[!WARNING] ⚠️ An infinite loop is easy to write. If your data has a cycle (employee A manages B, B manages A), the recursion never stops.
| Protection | 🟥 MSSQL | 🟦 MySQL |
|---|---|---|
| Default depth limit | 100 | 1000 |
| Change it | OPTION (MAXRECURSION 500) |
SET SESSION cte_max_recursion_depth = 5000; |
| Unlimited (dangerous) | OPTION (MAXRECURSION 0) |
set a very high value |
-- ✅ 🟥 MSSQL — defensive: add an explicit depth guard to the recursive member,
-- so a cycle in the data cannot loop forever (in MySQL, write WITH RECURSIVE)
WITH org_chart AS (
SELECT employee_id, first_name, manager_id, 0 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.first_name, e.manager_id, oc.level + 1
FROM employees e
INNER JOIN org_chart oc ON oc.employee_id = e.manager_id
WHERE oc.level < 20 -- 🔑 the guard
)
SELECT employee_id, first_name, level FROM org_chart ORDER BY level;
31.6 🔀 CTE vs derived table vs temp table
| CTE | Derived table | Temp table | |
|---|---|---|---|
| Readability | ✅ Best | ⚠️ Nests badly | ✅ Good |
| Reusable in the same query | ✅ Yes, by name | ❌ No | ✅ Yes |
| Persists across statements | ❌ No | ❌ No | ✅ Yes |
| Can be indexed | ❌ No | ❌ No | ✅ Yes |
| Has statistics (data summaries the optimizer uses) | ❌ No | ❌ No | ✅ Yes |
| Recursion | ✅ Yes | ❌ No | ❌ No |
| Worked out only once (materialized) | ⚠️ Usually not — may re-run each time it is used | ⚠️ Usually not | ✅ Always |
[!WARNING] ⚠️ The biggest CTE misconception: a CTE is not a temporary table. In MSSQL the CTE’s text is simply pasted into the query wherever you use it, so using the same CTE three times can run it three times. If a CTE is expensive and used several times, use a
#temptable instead. MySQL 8.0 may store a CTE’s result once, but do not rely on either behaviour — check the execution plan.
31.7 🎯 When to reach for a CTE
| Situation | Use |
|---|---|
| A subquery is used once and is short | Just write it in place — a CTE adds typing for no gain |
| The same derived result is needed twice in one query | ✅ CTE (named once, read twice) |
| Your query is nesting 3+ levels of parentheses | ✅ CTE — split it into named steps |
| A multi-step report: totals → per customer → classify → summarize | ✅ Chained CTEs |
| Walking a hierarchy or generating a sequence | ✅ Recursive CTE — nothing else does this |
| The intermediate result is large and used several times | ⚠️ A #temp table — a CTE may re-run per reference |
| You need an index on the intermediate result | ❌ Not a CTE — use a temp table |
| You need it across several statements | ❌ Not a CTE — a CTE only lasts until the end of its statement |
[!CAUTION] 🐛 Common mistake: assuming a CTE is stored like a temporary table. In SQL Server its text is pasted in wherever it is used, so a CTE used three times can be run three times. If it is expensive, that is a 3x cost you cannot see in the query text. Check the plan; if it is repeated, switch to a temp table.
31.8 🧪 Try it yourself
- Rewrite the “customers above the average spend” query from Chapter 30 using a CTE. Count how many lines you saved.
- Build the full org chart with indentation and levels.
- Generate every date in June 2026 and left-join daily order counts, showing 0 for quiet days.
- Write a recursive CTE that produces the numbers 1 to 100.
- Add a deliberate cycle to
employees(A manages B, B manages A) and watch the recursion limit protect you.
🧭 In practice — CTEs and recursive queries
How to use it. Put
WITH name AS (SELECT ...)before your main query and then treatnameas a table. Chain several, separated by commas, each able to reference the ones before it. For hierarchies, use a recursive CTE: an anchor query,UNION ALL, and a member that joins back to the CTE itself. MySQL requires theRECURSIVEkeyword. Expected result: a query that reads top to bottom as a sequence of named steps.When to use it. When a query has grown into nested parentheses nobody can safely edit, and whenever you need to walk a tree — an org chart, nested categories, a bill of materials.
Where to use it. Reporting and hierarchy traversal. Scenario: ShopDB’s
employees.manager_idpoints at another employee. A recursive CTE walks from the top down, producing each person’s depth and their full reporting path — something no fixed number of joins can do, because you do not know the depth in advance.When not to use it. A CTE is not automatically a performance improvement and it is not a temporary table — in SQL Server it is usually inlined, so a CTE referenced three times may be executed three times. When you need the result materialised once, use a temporary table (Chapter 40). Avoid recursion where a simple join suffices.
Best practices. Always give a recursive CTE a termination guarantee — a depth counter with a limit, or confidence that the data really is acyclic. One bad row creating a cycle turns the query into an infinite loop; SQL Server stops at 100 levels by default (
MAXRECURSION), MySQL atcte_max_recursion_depth, and both limits exist because this happens. Name each step for what it produces, since the names are the documentation.
32. APPLY and LATERAL
| 🎚️ Level | ⏱️ Time | 🎯 After this chapter you can… |
|---|---|---|
| 🟡🔴 Intermediate–Expert | 20 min | Get the top N rows for every group · Run a small query for each row · Split comma-separated text into rows |
[!NOTE] 📌 In plain words:
APPLY(MSSQL) andLATERAL(MySQL) let a subquery in theFROMclause look at columns from the row currently being processed. A normal derived table cannot do that.
🌍 Analogy: A normal join says “here are two finished lists, match them up.”
APPLYsays “for each row on the left, go and run this query specially for it.” It behaves like a “for each row” loop, but the database still runs it efficiently as one statement.
32.1 🎯 The problem they solve: top-N per group
“Show me the 2 most expensive products in each category.” This is genuinely awkward without APPLY.
-- 🟥 MSSQL: CROSS APPLY
SELECT
c.category_name,
top_p.product_name,
top_p.unit_price
FROM categories AS c
CROSS APPLY (
SELECT TOP 2 p.product_name, p.unit_price
FROM products p
WHERE p.category_id = c.category_id -- 🔑 references the OUTER row
ORDER BY p.unit_price DESC
) AS top_p
ORDER BY c.category_name, top_p.unit_price DESC;
-- 🟦 MySQL 8.0.14+: LATERAL
SELECT
c.category_name,
top_p.product_name,
top_p.unit_price
FROM categories AS c
JOIN LATERAL (
SELECT p.product_name, p.unit_price
FROM products p
WHERE p.category_id = c.category_id
ORDER BY p.unit_price DESC
LIMIT 2
) AS top_p ON TRUE
ORDER BY c.category_name, top_p.unit_price DESC;
[!TIP] 💡
ON TRUEis required syntax in MySQL’sLATERAL— the matching already happens inside the subquery, so the join condition is just a formality.
32.2 🔀 CROSS APPLY vs OUTER APPLY
CROSS APPLY |
OUTER APPLY |
|
|---|---|---|
| Left row with no matches | ❌ Dropped | ✅ Kept, with NULLs |
| Equivalent to | INNER JOIN |
LEFT JOIN |
-- 🟥 MSSQL: every customer plus their most recent order — including customers with none
SELECT
c.full_name,
last_order.order_id,
last_order.order_date,
last_order.status
FROM customers AS c
OUTER APPLY (
SELECT TOP 1 o.order_id, o.order_date, o.status
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY o.order_date DESC
) AS last_order
ORDER BY last_order.order_date DESC;
-- 🟦 MySQL: LEFT JOIN LATERAL
SELECT
c.full_name,
last_order.order_id,
last_order.order_date,
last_order.status
FROM customers AS c
LEFT JOIN LATERAL (
SELECT o.order_id, o.order_date, o.status
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY o.order_date DESC
LIMIT 1
) AS last_order ON TRUE
ORDER BY last_order.order_date DESC;
32.3 🧰 Other things APPLY is great at
-- 🟥 MSSQL: reuse a calculation without repeating it everywhere
SELECT
oi.order_id,
oi.product_id,
calc.line_total,
calc.line_total * 0.15 AS tax,
calc.line_total * 1.15 AS total_with_tax
FROM order_items AS oi
CROSS APPLY (
SELECT oi.unit_price * oi.quantity * (1 - oi.discount) AS line_total
) AS calc;
[!TIP] 💡 That is a lovely trick. Without
APPLYyou would repeat theunit_price * quantity * (1 - discount)expression three times. With it, you name the calculation once and reuse it. MySQL has no direct equivalent — use a derived table or CTE.
-- 🟥 MSSQL: splitting comma-separated text into rows (SQL Server 2016+)
-- ShopDB has no comma-separated column, so add one to try this:
ALTER TABLE customers ADD tags NVARCHAR(200) NULL;
GO -- 🔑 the new column only exists after this batch has run
UPDATE customers SET tags = 'vip,newsletter,early-access' WHERE customer_id = 1;
UPDATE customers SET tags = 'newsletter' WHERE customer_id = 2;
GO
SELECT
c.customer_id,
c.full_name,
TRIM(s.value) AS tag
FROM customers AS c
CROSS APPLY STRING_SPLIT(c.tags, ',') AS s
WHERE c.tags IS NOT NULL;
Result:
| customer_id | full_name | tag |
|---|---|---|
| 1 | Amara Silva | vip |
| 1 | Amara Silva | newsletter |
| 1 | Amara Silva | early-access |
| 2 | John Baker | newsletter |
[!TIP] 💡 Note that
CROSS APPLYdrops customers whosetagsis NULL —STRING_SPLIT(NULL, ',')returns no rows. Swap inOUTER APPLYif you want to keep them. And remember: a comma-separated column breaks the first rule of good table design (1NF, Chapter 51) — this technique is for cleaning up data you inherited, not for data you design.
32.4 ⚖️ APPLY vs window functions for top-N
Both solve “top N per group”. Which to use?
-- ✅ The window function alternative (works in BOTH) — see Chapter 33
WITH ranked AS (
SELECT
p.product_name,
p.unit_price,
c.category_name,
ROW_NUMBER() OVER (PARTITION BY p.category_id ORDER BY p.unit_price DESC) AS rn
FROM products p
JOIN categories c ON c.category_id = p.category_id
)
SELECT category_name, product_name, unit_price
FROM ranked
WHERE rn <= 2
ORDER BY category_name, unit_price DESC;
APPLY / LATERAL |
Window function | |
|---|---|---|
| Works in | ⚠️ MSSQL / MySQL 8.0.14+ | ✅ Every modern database |
| Speed for small N per group | ⚡ Often faster (uses the index, stops early) | Must rank every row first |
| Speed when the outer table is huge | ⚠️ Runs per outer row | ✅ One pass |
| Readability | ✅ Very direct | ✅ Clean once you know it |
[!TIP] 💡 Rule of thumb: for “top 1 or 2 per group” with a good index,
APPLY/LATERALusually wins. For anything needing ranks, ties, or running totals, use window functions. When in doubt, test both and compare their execution plans (Chapter 47).
32.5 🧪 Try it yourself
- Show the 3 best-selling products in each category.
- Show every customer with their most recent order, including customers who have none.
- For each employee, show the single largest order they handled.
- Solve the same problem with
ROW_NUMBER()and compare execution plans.
🧭 In practice — APPLY and LATERAL
How to use it.
CROSS APPLY(SQL Server) andLATERAL(MySQL 8.0.14+) let a subquery in theFROMclause reference columns from the row to its left — something a normal join cannot do.OUTER APPLY/LEFT JOIN LATERALkeeps left rows with no match. Expected result: a per-row subquery, evaluated once per outer row.When to use it. For top-N per group — the three most expensive products in each category, each customer’s most recent order — and for calling a table-valued function per row.
Where to use it. Reporting queries that need a small slice per group. Scenario: “the two newest orders for each customer”.
CROSS APPLYwithTOP 2 ... ORDER BY order_date DESCcan use an index and stop after two rows per customer, whereas ranking every order with a window function sorts the entire table first.When not to use it. Avoid it when the outer table is large and the inner query is expensive — it runs per outer row, so cost scales with the number of rows. In that case a window function’s single pass wins. Avoid it entirely if portability matters: the syntax differs between engines, and MySQL only gained
LATERALin 8.0.14.Best practices. Choose between
APPLYand a window function by shape, not habit: small N per group over an indexed column favoursAPPLY; a computation over every row favours the window function. Measure both on your data — this is one of the few places where two correct queries differ in cost by an order of magnitude in either direction depending on the statistics.
| Part index | Prerequisites | Previous | Next | Full course |