SQL joins interview questions and answers, from basics to execution
SQL join interview questions are less about naming the join types and more about predicting the exact rows a query returns. Interviewers hand you two or three small tables and ask what a LEFT JOIN with a filter, a NOT IN against a column with NULLs, or a join to a payments table will produce, then ask you to fix it. Say the grain of each table before you write the join, and check the row count after it.
By Evin JohnPublished 10 min read
Why joins get a round of their own
Almost every data analyst, data engineer, backend and BI interview reaches joins within the first ten minutes, because a wrong join is the most common way a report ends up confidently wrong. The broad topics (GROUP BY, window functions, CTEs, transactions) live in SQL interview questions. This page stays on joins and goes deeper: the semantics, the traps that change row counts, and the execution questions that come up for senior candidates.
- Predict the outputTwo tiny tables on a whiteboard or in a doc, and the question "how many rows, and which ones?" for an inner, left or full join.
- Write the queryCustomers without orders, employees and their managers, orders matched to a price band, records missing from one of two systems.
- Debug a numberA revenue total that doubled after a join was added, or a left join that lost rows. You are expected to find the cause, not rewrite blindly.
- Explain performanceWhich join algorithm the engine might choose, why an index on the foreign key matters, and what you would read in the plan.
Join fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does an INNER JOIN return? | Core semantics | Only row pairs where the ON condition is true. A left row with no partner disappears, and a left row with three partners appears three times. |
| LEFT JOIN versus RIGHT JOIN? | Direction | LEFT keeps every row from the table written first; RIGHT keeps every row from the second. Any RIGHT JOIN can be rewritten as a LEFT JOIN by swapping the tables, which most teams prefer for readability. |
| What does FULL OUTER JOIN give you? | Outer joins | Every row from both sides: matched pairs, left rows padded with NULLs and right rows padded with NULLs. MySQL lacks it, so there you union a left join with the unmatched rows of a right join. |
| What is a CROSS JOIN and when is it useful? | Cartesian product | Every left row paired with every right row. Useful for building a calendar of every store times every day, dangerous when it happens by accident through a missing condition. |
| Why are Venn diagrams a weak model for joins? | Mental model | They show sets, but joins multiply rows. One customer with four orders becomes four rows, which no circle overlap shows. A grid of row pairs filtered by a condition is closer to the truth. |
| ON versus USING? | Syntax | USING(customer_id) joins on equally named columns and merges them into one output column. ON allows any condition, including different names, ranges and extra filters. |
| Why do many teams avoid NATURAL JOIN? | Maintainability | It joins on every column with the same name, so adding a column such as updated_at to both tables silently changes the join. |
| Does a NULL key ever match in an equality join? | NULL logic | No. NULL = NULL is unknown, not true, so rows with NULL keys never pair up. If NULLs must match, join on a COALESCE to a sentinel or use IS NOT DISTINCT FROM where the engine supports it. |
| Does the order of tables in an inner join change the result? | Optimizer | Not the result set. The optimizer is free to reorder inner joins. Order does matter once outer joins are mixed in, because the preserved side changes. |
| Is a join with a condition in WHERE the same as one in ON? | Inner joins | For an inner join, yes, the two give the same rows. For an outer join, no, and that difference is the next section. |
Outer joins and where the filter goes
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, region TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status TEXT, amount REAL);
INSERT INTO customers VALUES (1,'Asha','EU'),(2,'Ben','US'),(3,'Chen','US'),(4,'Dana',NULL);
INSERT INTO orders VALUES (10,1,'shipped',120),(11,1,'cancelled',40),(12,2,'shipped',80),(13,NULL,'shipped',15);
-- Filter inside ON: every customer stays, only shipped orders attach.
SELECT c.name, o.id AS order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'shipped';
-- Asha|10 Ben|12 Chen|NULL Dana|NULL
-- Same filter in WHERE: NULL status fails the test, so Chen and Dana vanish.
SELECT c.name, o.id AS order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'shipped';
-- Asha|10 Ben|12- Why did the second query lose rows? For Chen and Dana the right side is all NULLs, and
NULL = 'shipped'is unknown, so WHERE discards them. The query now behaves like an inner join while still saying LEFT JOIN. - When does a filter belong in WHERE on an outer join? When it is on the preserved table (
WHERE c.region = 'US'), or when you deliberately test for absence withWHERE o.id IS NULL. - How do you count customers with zero orders next to everyone else? LEFT JOIN, then
COUNT(o.id), notCOUNT(*). COUNT(*) counts the padded row and reports one order for people who have none. - What happens when you chain a LEFT JOIN and then an INNER JOIN to a third table? The inner join drops rows where the second table was NULL, undoing the left join. Make the later join a LEFT JOIN too, or join the second and third tables first in a subquery.
- Order 13 has no customer. Which join shows it? A RIGHT JOIN from customers, a LEFT JOIN from orders, or a FULL OUTER JOIN. An orphan row like this is usually a data quality question worth raising out loud.
Anti-joins, semi-joins and the NOT IN trap
-- Customers who never ordered: NOT EXISTS
SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- Chen Dana
-- The same question with NOT IN returns no rows at all
SELECT c.name FROM customers c
WHERE c.id NOT IN (SELECT customer_id FROM orders);
-- (empty)| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why does NOT IN return nothing here? | Three-valued logic | 3 NOT IN (1, 2, NULL) expands to 3 <> 1 AND 3 <> 2 AND 3 <> NULL. The last part is unknown, so the whole test is never true for any row. |
| Three ways to write an anti-join? | Patterns | NOT EXISTS, LEFT JOIN with WHERE right.key IS NULL, and EXCEPT on key columns. NOT EXISTS is the safest default because NULLs in the subquery cannot break it. |
| What is a semi-join? | Existence | Return each left row once if at least one match exists, without repeating it per match. EXISTS and IN express it; a plain inner join would duplicate the row. |
| Inner join plus DISTINCT, or EXISTS? | Intent and cost | EXISTS says what you mean and can stop at the first match. DISTINCT after a join builds the duplicates and then removes them, and it can also collapse rows that were legitimately different. |
| In a LEFT JOIN anti-join, which column do you test for NULL? | Correctness | A column that can never be NULL in a real match, normally the right table's primary key. Testing a nullable column picks up matched rows whose value happens to be NULL. |
| Is EXCEPT the same as NOT EXISTS? | Set operations | Close, but EXCEPT compares whole selected rows, removes duplicates, and treats NULLs as equal to each other. Use it when you compare key lists, not full records. |
Self-joins, range joins and reconciliation
CREATE TABLE employees (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER, salary INTEGER);
INSERT INTO employees VALUES (1,'Rosa',NULL,200),(2,'Sam',1,150),(3,'Tia',1,210),(4,'Uma',2,90);
-- Who earns more than their own manager?
SELECT e.name
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
-- Tia
CREATE TABLE shipments (id INTEGER PRIMARY KEY, weight_kg REAL);
CREATE TABLE rate_bands (min_kg REAL, max_kg REAL, band TEXT);
INSERT INTO shipments VALUES (1,0.4),(2,2.0),(3,7.5),(4,40);
INSERT INTO rate_bands VALUES (0,1,'small'),(1,5,'medium'),(5,20,'large');
-- Half-open ranges: a 1 kg parcel lands in exactly one band
SELECT s.id, s.weight_kg, r.band
FROM shipments s
LEFT JOIN rate_bands r
ON s.weight_kg >= r.min_kg AND s.weight_kg < r.max_kg;
-- 1|0.4|small 2|2.0|medium 3|7.5|large 4|40.0|NULL- Why alias the same table twice in a self-join? Each alias is a separate role, employee and manager. Without aliases the column references are ambiguous, and with lazy aliases (a, b) the reader cannot tell which side is which.
- Why LEFT JOIN for the manager list? The top of the hierarchy has no manager. An inner join silently drops the CEO from an org report.
- What can go wrong with a range join? Overlapping bands return two rows for one shipment, and gaps return none. Half-open intervals (>= lower, < upper) prevent the double match at the boundary, and the 40 kg parcel shows a gap someone should own.
- How would you match each event to the price in effect at that moment? Join on the product and
event_time >= valid_from AND event_time < valid_toon a history table, with an open end date for the current row. This is the classic point-in-time join on a slowly changing dimension. - How do you find pairs of rows that overlap in time, such as double-booked rooms? Self-join on the room with
a.start < b.end AND b.start < a.end AND a.id < b.id. The last condition stops each pair from appearing twice and a row from matching itself.
CREATE TABLE ledger (invoice TEXT, amount REAL);
CREATE TABLE bank (invoice TEXT, amount REAL);
INSERT INTO ledger VALUES ('A-1',100),('A-2',250),('A-3',75);
INSERT INTO bank VALUES ('A-1',100),('A-2',240),('A-4',30);
SELECT COALESCE(l.invoice, b.invoice) AS invoice,
l.amount AS ledger_amt, b.amount AS bank_amt,
CASE WHEN l.invoice IS NULL THEN 'missing in ledger'
WHEN b.invoice IS NULL THEN 'missing in bank'
WHEN l.amount <> b.amount THEN 'amount differs'
ELSE 'ok' END AS result
FROM ledger l
FULL OUTER JOIN bank b ON b.invoice = l.invoice
ORDER BY invoice;
-- A-1|100.0|100.0|ok
-- A-2|250.0|240.0|amount differs
-- A-3|75.0|NULL|missing in bank
-- A-4|NULL|30.0|missing in ledgerGrain, fan-out and duplicate rows
Grain means what one row represents: one order, one payment, one order per day. Fan-out happens when you join a table to another at a finer grain and then sum a column from the coarser one. Order 10 below was paid in two installments, so its amount is counted twice after the join.
CREATE TABLE payments (id INTEGER PRIMARY KEY, order_id INTEGER, paid REAL);
INSERT INTO payments VALUES (100,10,60),(101,10,60),(102,12,80);
-- Wrong: order 10 (120) appears once per payment
SELECT SUM(o.amount) AS revenue
FROM orders o JOIN payments p ON p.order_id = o.id;
-- 320.0
-- Right: bring payments to one row per order before joining
WITH paid AS (
SELECT order_id, SUM(paid) AS paid FROM payments GROUP BY order_id
)
SELECT SUM(o.amount) AS revenue, SUM(paid.paid) AS collected
FROM orders o JOIN paid ON paid.order_id = o.id;
-- 200.0|200.0- How do you catch fan-out before it reaches a dashboard? Count rows and distinct keys before and after each join. If an order-level query has more rows than distinct order IDs, a join multiplied it.
- Two one-to-many joins from the same parent, say orders to items and orders to shipments? Each order now has items times shipments rows. Aggregate each child to the order first, then join the two summaries.
- Is SUM(DISTINCT amount) a fix? No. It also merges two different orders that share an amount. Fix the grain instead of hiding the duplicates.
- How do you model a many-to-many relationship such as students and courses? A bridge table (enrollments) with one row per pair, keyed on both IDs, and two joins through it. Questions about which students share a course are a self-join on the bridge.
- A dimension table has two rows for the same key. What breaks? Every fact row matching that key doubles. Enforce uniqueness with a constraint where possible, and add a duplicate-key check to the pipeline where not.
Senior questions: how the database runs a join
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Nested loop, hash join and merge join: when does each win? | Algorithms | Nested loop suits a small outer input with an index on the inner key. Hash join builds a hash table on the smaller input and suits large unsorted equality joins. Merge join walks two inputs already sorted on the key. |
| Which join can a hash join not handle? | Limits | Non-equality conditions such as ranges. Those usually fall back to nested loops, which is why big range joins need care or a different design. |
| Why index foreign keys? | Indexing | Joins and lookups from the parent use them, and so do deletes on the parent that must check children. Many engines do not index foreign keys automatically. |
| The plan estimated 10 rows and got 2 million. Why does it matter? | Statistics | The optimizer picked a nested loop for 10 rows and now runs it 2 million times. Stale statistics, correlated columns and functions on join keys are common causes. |
| Why might wrapping a join key in a function slow the query? | Sargability | ON LOWER(a.email) = LOWER(b.email) stops a plain index from being used. Store a normalized column or build an expression index where the engine supports it. |
| What happens when join keys have different types? | Implicit casts | A text key joined to an integer key forces a conversion on one side, which can skip the index and also mismatch values such as '007' and 7. |
| How do distributed engines join two large tables? | Scale | They shuffle both sides by the join key so matching rows meet on the same worker, or broadcast the small side to every worker. Skewed keys, such as a default customer ID, overload one worker. |
| How would you join a 2 TB events table to a small lookup table? | Design | Broadcast or hash the lookup side, filter and project events before the join, and check that the lookup has one row per key so nothing multiplies. |
Fictional example
- Interviewer
- Revenue on the dashboard jumped after an analyst joined a refunds table. Sales did not change. Walk me through it.
- Candidate
- My first guess is grain. Revenue is one row per order and refunds are one row per refund event, so an order with two partial refunds now appears twice and its amount is summed twice. I would confirm it by counting rows against distinct order IDs before and after the join. If they differ, I aggregate refunds to one row per order in a CTE and left join that, so orders with no refund stay in with a zero after COALESCE. Then I would compare the new weekly total with last month's known-good figure, and suggest a uniqueness check on the joined key so the next change fails loudly instead of quietly.
A one-week join practice plan
- Day 1: build the customers, orders and payments tables above in sqlite3. Before running each join type, write down the rows you expect, then compare.
- Day 2: move one filter between ON and WHERE in five different queries and explain each change in row count out loud.
- Day 3: write every anti-join three ways, then insert a NULL into the subquery column and watch which version breaks.
- Day 4: practice self-joins and overlap checks: managers, double bookings, consecutive logins.
- Day 5: take a report with two child tables and fix the fan-out by aggregating first. Add row-count checks.
- Days 6 and 7: read query plans for your joins with EXPLAIN in the database you will be interviewed on, and be ready to say why the engine picked each algorithm.
Joins show up across several neighboring loops. The data analyst interview questions and data engineer interview questions pages show where they sit in a full interview. Reporting on device inventory is a join-heavy job too, as the SCCM interview questions page shows, and Java backend roles reach SQL through the web tier described in Servlet interview questions.
Join questions reward predicting before running, and that habit is easy to lose under pressure. Natively, an AI interview assistant for Mac and Windows, transcribes a mock SQL round on your machine, so you can check afterward whether you stated the grain and the expected row count before you typed. During practice it can read a schema or a query from a screenshot and point out a likely fan-out or NULL trap. With Pro or the free trial it can also use the résumé and job description you add, and it keeps the transcript and notes for review.
Questions people ask
What SQL join questions are asked in interviews?
Expect to predict the rows of inner, left and full outer joins, find records with no match, write a self-join for managers, fix a total inflated by a join, and explain why a filter in WHERE changed a left join.
What is the difference between a filter in ON and in WHERE for a LEFT JOIN?
In ON the filter only decides which right rows attach, so every left row stays. In WHERE it runs after the join and removes the NULL-padded rows, which turns the query into an inner join.
Why does NOT IN return no rows when the subquery has a NULL?
Each comparison with NULL is unknown rather than true, so the NOT IN test is never true. NOT EXISTS or a LEFT JOIN with an IS NULL check avoids the problem.
Why does a join make my SUM too large?
The joined table has several rows per key, so each row from the other side repeats. Aggregate the many side to the right grain before joining, and compare row counts before and after.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
