Interview Q&A · SQL · 14 questions in this topic
JOINs In Depth — SQL Interview Q&A
Combining tables — every join type, the ON vs WHERE distinction, self-joins and join performance. Part of JOINs · 192 questions in the SQL bank.
What is a JOIN and how does INNER JOIN work?
Answer
JOIN combines rows from two tables on a matching condition (usually foreign key = primary key). INNER JOIN keeps only pairs matching on both sides — non-matching rows vanish from both tables.
Unmatched-row questions need OUTER joins; INNER is the intersection of the relationship.
Example
SELECT e.name, d.location
FROM employees e
INNER JOIN departments d ON e.department = d.dept_id;💡 Only-matching-pairs-survive is the INNER mental model.
How do LEFT, RIGHT and FULL OUTER JOIN differ?
Answer
LEFT keeps every left row, filling NULLs where no right match exists. RIGHT mirrors (every right row kept). FULL keeps both sides' orphans with NULLs on the missing side. INNER keeps only matches.
LEFT is the workhorse (find orphans, optional relations); RIGHT is rare (swap table order instead); FULL audits two-sided completeness.
Key points
- 1INNER — matches only.
- 2LEFT — all left rows, NULLs for misses.
- 3FULL — all rows both sides, NULLs for misses.
Example
-- employees with no department match: SELECT e.* FROM employees e LEFT JOIN departments d ON e.department = d.dept_id WHERE d.dept_id IS NULL;
💡 LEFT-plus-IS-NULL is the orphan-finder to memorize.
What is the difference between ON and WHERE in an OUTER JOIN?
Answer
ON decides matching during the join — non-matching left rows survive a LEFT JOIN with NULLs. WHERE filters after — testing the nullable side (WHERE d.x = 1) kills the NULL rows, silently converting the LEFT JOIN into an INNER JOIN.
Rule: match conditions in ON; keep the outer-ness by testing nullable columns only for IS NULL, or move filters into ON.
Example
-- stays LEFT (filter inside ON): SELECT * FROM employees e LEFT JOIN departments d ON e.department = d.dept_id AND d.location = 'Berlin'; -- becomes INNER (filter after): -- ... WHERE d.location = 'Berlin';
What are SELF JOIN, CROSS JOIN and non-equi joins?
Answer
SELF JOIN joins a table to itself with aliases — hierarchies (employee/manager), pairs, consecutive rows. CROSS JOIN produces the full cartesian product (every combination — usually a missing-ON bug, deliberately for grids). Non-equi joins match on ranges/inequalities (bands, intervals) instead of equality.
Alias discipline makes self-joins readable; row-count explosion awareness makes CROSS safe.
Example
-- manager names via self join: SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id;
How do multiple JOINs chain, and does order matter?
Answer
JOINs evaluate left-to-right; each result feeds the next. INNER chains commute freely (planner reorders anyway). OUTER chains do not commute — (A LEFT B) LEFT C differs from A LEFT (B LEFT C) in NULL propagation. Parenthesize or sequence deliberately.
Read chains as pipelines: left result, plus right matches, step by step.
Example
SELECT * FROM employees e LEFT JOIN departments d ON e.department = d.dept_id LEFT JOIN locations l ON d.location = l.city;
💡 INNER commutes, OUTER nests — the ordering rule in four words.
What is a NATURAL JOIN / USING, and should you use them?
Answer
NATURAL JOIN matches on all same-named columns implicitly; USING(col) matches on listed shared columns and coalesces them into one output column. Both hide the join keys — a schema change (new same-named column) silently alters results.
Explicit ON is reviewable and stable; USING is acceptable in disciplined schemas; NATURAL JOIN is widely considered a footgun.
Example
-- explicit (preferred): SELECT * FROM employees e JOIN departments d ON e.department = d.dept_id; -- USING form: single dept_id in output -- ... JOIN departments USING (dept_id);
💡 Explicit ON survives schema evolution; implicit forms do not.
How do you join on ranges (band join, date-effective join)?
Answer
Inequality ON conditions match rows into bands: salary to pay-grade ranges, events to effective-dated versions (start <= event < end). These are non-equi joins — correct but heavier (nested-loop-ish plans); composite/covering indexes on the range columns help.
Point-in-time correctness (which version was live then?) lives or dies on the half-open end.
Example
-- salary band lookup: SELECT e.name, b.band FROM employees e JOIN pay_bands b ON e.salary BETWEEN b.lo AND b.hi;
What is the difference between `JOIN` and `UNION`?
Answer
JOIN widens rows — adds columns by matching tables side-by-side. UNION stacks result sets — adds rows, requiring identical column counts/types. JOIN asks across entities; UNION combines same-shaped results.
Mixing them up produces either column explosions or type errors — the question tests dimensional thinking.
Example
-- JOIN: wider rows -- SELECT e.name, d.location FROM employees e JOIN departments d ... -- UNION: taller result SELECT name FROM employees UNION SELECT head FROM departments;
💡 JOIN widens, UNION lengthens is the dimensional summary.
Why do JOINs multiply rows (fan-out), and how do you control it?
Answer
One-to-many matches replicate the one-side row per match — aggregating after a fan-out double-counts (SUM over duplicated salaries). Control by pre-aggregating the many-side first (subquery/CTE grouped to one row per key), joining on true keys, or using semi-joins (EXISTS) for existence checks.
Aggregate-before-join is the canonical fix; fan-out-aware review is the habit.
Example
-- pre-aggregate the many side first: SELECT d.dept_id, COALESCE(t.total, 0) FROM departments d LEFT JOIN (SELECT department, SUM(salary) AS total FROM employees GROUP BY department) t ON t.department = d.dept_id;
How do you join with aggregation (per-group joins)?
Answer
Aggregate the detail table to one row per key in a derived table/CTE, then join — the fan-out-proof pattern. Or join first and GROUP BY the dimension (safe only over true one-to-one keys). LATERAL (PostgreSQL) runs a per-row subquery for top-N-per-group style needs.
Derived-aggregate-then-join is the default shape.
Example
SELECT d.dept_id, t.n, t.avg_pay FROM departments d JOIN (SELECT department, COUNT(*) n, AVG(salary) avg_pay FROM employees GROUP BY department) t ON t.department = d.dept_id;
What join algorithms exist (nested loop, hash, merge)?
Answer
Nested loop: for each outer row, probe inner (great for small/selective, index lookups). Hash: build hash of one side, probe with the other (great for large equi-joins). Merge: co-scan two sorted inputs (great when indexes provide order). EXPLAIN reveals the choice; missing indexes force nested loops over scans.
You do not pick them directly — you shape data and indexes so the planner can.
Key points
- 1Nested loop — small outer, indexed inner.
- 2Hash — big equi-joins.
- 3Merge — pre-sorted inputs.
Example
-- EXPLAIN shows: Nested Loop, Hash Join, or Merge Join
💡 Name all three with one best-case each — the complete algorithm answer.
How do you make JOINs fast?
Answer
Index the join keys on both sides (foreign-key indexes are not automatic everywhere), filter early (WHERE before JOIN width), join on narrow typed-identical keys, and avoid functions/conversions on join columns. Check EXPLAIN for the algorithm and row estimates.
Unindexed foreign keys also slow every parent DELETE (child scans) — index them for write health too.
Key points
- 1Index both join keys, identical types.
- 2Filter before widening.
- 3Verify with EXPLAIN.
Example
CREATE INDEX idx_emp_dept ON employees (department);💡 Index-the-FK is the single highest-value join advice.
How do you find orphaned rows (broken foreign keys without constraints)?
Answer
LEFT JOIN from child to parent with WHERE parent.key IS NULL — orphans surface. NOT EXISTS form is equivalent and NULL-safe. Periodic orphan audits are the data-quality backstop where constraints were skipped.
Then add the missing FOREIGN KEY to stop recurrence — audit plus constraint is the complete fix.
Example
SELECT e.* FROM employees e LEFT JOIN departments d ON e.department = d.dept_id WHERE d.dept_id IS NULL; -- orphans
What is a semi-join / anti-join (EXISTS vs JOIN)?
Answer
Semi-join (EXISTS/IN) returns left rows having a match — without duplicating them on multi-match. Anti-join (NOT EXISTS) returns left rows with no match. Both avoid fan-out by construction, unlike equivalent JOINs needing DISTINCT.
Existence questions want EXISTS; row-combining questions want JOIN — matching the operator to the question.
Example
-- departments that HAVE employees (no duplication): SELECT * FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department = d.dept_id);
💡 Existence without duplication is the semi-join value proposition.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission