12 questions on SQL joins, tagged easy, medium or hard, each with a worked answer in runnable SQL.
One schema throughout. The answers use the small shop schema shown here. Dialect-specific examples name the engine they are written for, and the few extra tables a question needs, such as subscribers or logins, are introduced where they appear.
Practice mode. To test yourself first, press Hide answers: each answer waits behind a Show answer button. The practice mode link deals a shuffled deck from every topic.
No questions at this difficulty on this page. Pick another filter.
1
What is the difference between an INNER JOIN and a LEFT JOIN?
Easy
INNER JOIN keeps only rows with a match on both sides. LEFT JOIN keeps every row of the left table; unmatched right-side columns come back NULL.
-- Only customers who have ordered:
SELECT c.name, o.order_id, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;
-- Every customer; orders columns are NULL when they never ordered:
SELECT c.name, o.order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
The classic check: with a LEFT JOIN, columns from the right table can be NULL either because there was no match or because the stored value is NULL. COALESCE only fixes the display; it does not tell you which happened.
2
Write a query that returns each customer and their order count, including customers with zero orders.
Easy
LEFT JOIN plus COUNT of the right table's key. Counting the right table's column is the whole trick, because COUNT(*) counts the NULL-extended rows too.
SELECT c.name, 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.name
ORDER BY order_count DESC;
With COUNT(*), a customer with no orders shows 1 instead of 0, because the LEFT JOIN produced one row for them with NULLs. The interview is really checking whether you know which column to count.
3
What is join fan-out, and how does it corrupt aggregates?
Средний
Fan-out happens when one row of a table matches several rows on the other side, so joined output has more rows than either input. Aggregates then double- or triple-count.
-- Each order has several order_items; joining then summing
-- counts each order total once per item line:
SELECT SUM(o.total) AS wrong_revenue -- inflated
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id;
-- Correct: collapse order_items to one row per order, then join:
SELECT SUM(o.total) AS revenue, SUM(i.lines) AS item_lines
FROM orders o
JOIN (
SELECT order_id, COUNT(*) AS lines
FROM order_items
GROUP BY order_id
) i ON i.order_id = o.order_id;
An order worth 100 with three item lines contributes 300 to the first query. Name the two fixes: aggregate the many side down to the grain of the one side before joining, or aggregate each table separately and join the results. SUM(DISTINCT o.total) is the tempting patch and it is wrong too: two different orders that both total 100 collapse into one.
4
How do you find rows in one table with no match in another (an anti-join)?
Средний
Two idiomatic ways. LEFT JOIN with IS NULL is the classic; NOT EXISTS states the intent directly. Both handle NULLs correctly, and PostgreSQL, SQL Server and MySQL 8.0.17+ usually plan them as the same anti-join.
-- Customers who never ordered (LEFT JOIN anti-join):
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; -- test a column that is never NULL in a real match
-- Same result, usually the better answer:
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
NOT IN is the trap: if the subquery returns even one NULL, NOT IN returns no rows at all, because x NOT IN (1, NULL) can never be proven true. Mentioning that unprompted is the senior signal in this question.
5
What does a FULL OUTER JOIN do, and when would you use it?
Средний
It keeps every row from both sides, matching where it can and filling NULLs where it cannot. Use it when comparing two datasets that should mirror each other, such as reconciling a source and a target table.
SELECT COALESCE(s.id, t.id) AS id, s.balance AS source_balance, t.balance AS target_balance
FROM source_balances s
FULL OUTER JOIN target_balances t ON t.id = s.id
WHERE s.id IS NULL OR t.id IS NULL -- mismatches only
OR s.balance <> t.balance;
A matched row where only one side's balance is NULL slips past the <> test, because comparing with NULL is unknown rather than true; s.balance IS DISTINCT FROM t.balance (PostgreSQL, SQLite, SQL Server 2022+; NOT (a <=> b) on MySQL) closes that gap. MySQL has no FULL OUTER JOIN, and SQLite only gained it in 3.39, which is the usual follow-up: emulate it with a LEFT JOIN unioned with a RIGHT JOIN, as the last question on this page shows.
6
What is a CROSS JOIN, and what is a legitimate use?
Easy
A CROSS JOIN is every row paired with every row (a Cartesian product). n rows times m rows produces n times m rows, usually by accident through a forgotten join condition.
-- Legitimate: build every day and product combination,
-- then left join actual sales onto that grid (PostgreSQL):
SELECT d.day, p.product_id, COALESCE(s.units, 0) AS units
FROM (
SELECT g::date AS day
FROM generate_series(DATE '2025-01-01', DATE '2025-01-31', INTERVAL '1 day') AS g
) d
CROSS JOIN products p
LEFT JOIN sales s ON s.day = d.day AND s.product_id = p.product_id;
CROSS JOIN is right when you need the complete grid of combinations, so that a product with no sales on a day shows 0 instead of having no row. Other engines build the calendar with a recursive CTE or a calendar table instead of generate_series. An accidental Cartesian product usually comes from an old-style comma join with a missing WHERE condition, and the symptom is a row count equal to the product of the two table sizes.
7
What is a self join, and how do you list each employee with their manager?
Средний
A self join joins a table to itself under two aliases. With employees.manager_id referencing employees.employee_id:
SELECT e.name AS employee,
m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.employee_id = e.manager_id
ORDER BY e.name;
It is a LEFT JOIN so the CEO, whose manager_id is NULL, still appears. The follow-up is usually how to get the whole reporting chain, which needs a recursive CTE rather than a fixed number of self joins.
8
What changes when you move a filter from the ON clause to WHERE in a LEFT JOIN?
Средний
For INNER JOINs nothing changes: ON and WHERE are logically equivalent. For LEFT JOINs it matters enormously, because WHERE runs after the join and its NULL-extended rows.
-- Keeps all customers, counts only delivered orders:
SELECT c.name, COUNT(o.order_id) AS delivered
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;
-- Turns the LEFT JOIN into an INNER JOIN effectively:
SELECT c.name, COUNT(o.order_id) AS delivered
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'delivered' -- kills the NULL rows
GROUP BY c.customer_id, c.name;
The rule to state: filters on the right (nullable) side go in ON if you want to keep unmatched left rows; WHERE is for filters on the left side or when you genuinely want the inner-join behavior.
9
What happens when you join on a key that has duplicates on either side?
Easy
Every matching pair produces a row. If the left key has n duplicates and the right has m, that key contributes n times m rows. Duplicates on one side multiply the other side's rows.
-- If customers had two rows for customer_id = 7 and orders has
-- three orders for that customer, the join returns 6 rows for them:
SELECT *
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id;
The defense is uniqueness, not hope: primary keys on the one side, and checking for duplicates with GROUP BY ... HAVING COUNT(*) > 1 when you inherit a schema. Fan-out plus aggregation is how double-counting bugs reach dashboards.
10
How do you join a table to an aggregate of another table without fan-out?
Средний
Aggregate first, then join the aggregate. Joining raw rows first and grouping afterwards works too, but only if you aggregate the right grain; the pre-aggregated join makes the intent explicit and the plan cheaper.
SELECT c.name, agg.total_spent
FROM customers c
JOIN (
SELECT customer_id, SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
) agg ON agg.customer_id = c.customer_id;
The window-function alternative keeps every order row and attaches each customer's total alongside, without collapsing rows: SUM(total) OVER (PARTITION BY customer_id). Say when each is right: pre-aggregated join when you want one row per customer, the window when you still need order-level rows.
11
How do you get the top three orders per customer?
Hard
Window functions or a correlated LATERAL join. The window version numbers every order and then throws most of them away; the LATERAL version runs a small query per customer that can stop after three rows when an index on (customer_id, total) supports it. Many customers with few orders each favors the window; few customers with long histories favors LATERAL.
-- ROW_NUMBER: rank within each customer, then filter outside:
SELECT customer_id, order_id, total
FROM (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY total DESC) AS rn
FROM orders o
) ranked
WHERE rn <= 3;
-- LATERAL (PostgreSQL, MySQL 8.0.14+). Oracle 12c+ has LATERAL too but writes
-- FETCH FIRST 3 ROWS ONLY; SQL Server spells it CROSS APPLY with TOP (3):
SELECT c.name, top_orders.order_id, top_orders.total
FROM customers c
CROSS JOIN LATERAL (
SELECT o.order_id, o.total
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY o.total DESC
LIMIT 3
) top_orders;
The nuance worth adding: ROW_NUMBER breaks ties arbitrarily, RANK gives ties the same rank and skips the next, DENSE_RANK skips nothing. Choose deliberately. The WHERE rn <= 3 must sit outside the subquery because window functions cannot appear in WHERE.
12
How do you emulate a FULL OUTER JOIN in MySQL?
Hard
Union a LEFT JOIN with a RIGHT JOIN, and keep rows from the second query only where the left side had no match. That WHERE clause is what prevents duplicates, which is why UNION ALL is safe here.
SELECT s.id, s.balance AS source_balance, t.balance AS target_balance
FROM source_balances s
LEFT JOIN target_balances t ON t.id = s.id
UNION ALL
SELECT t.id, s.balance, t.balance
FROM source_balances s
RIGHT JOIN target_balances t ON t.id = s.id
WHERE s.id IS NULL;
The first half returns every source row, matched or not. The second half returns only target rows with no source match. Note the second branch selects t.id: s.id is NULL on exactly those rows, so selecting it would print an id of NULL. Plain UNION instead of UNION ALL plus the filter also looks right, but it silently merges genuinely duplicate rows.
SQL joins interview FAQ
Which join types do these questions cover?
INNER, LEFT and FULL OUTER joins, CROSS JOIN, self joins, anti-joins, and correlated LATERAL joins for top-n-per-group problems.
What is the hardest question here?
The top three orders per customer with LATERAL, and simulating a FULL OUTER JOIN in engines that do not have one. Both come up regularly in senior interviews.
Do the answers explain the classic LEFT JOIN mistakes?
Yes: rows duplicated by join fan-out, filters drifting from ON to WHERE and changing the result, and counting the wrong column so zero-order customers disappear.
Is there a way to test myself on these?
Press Hide answers next to the question list: every answer collapses behind a Show answer button and a counter tracks how many you have opened. Practice mode, linked at the top, deals a shuffled deck from all seven topics instead.
SQLly is a native SQL workbench for macOS, Windows and Linux: IntelliSense that knows your
schema, a formatter, guardrails for risky queries, and every engine in one app.