SQL Joins and Set Operations Questions
Combining data across multiple tables using inner, outer, cross, and self joins, plus set operations (UNION, INTERSECT, EXCEPT). Covers join-key selection, fan-out and row-multiplication pitfalls, merge strategies, and integrating data from disparate sources. A high-frequency interview surface for anyone who queries relational data.
Given a referrals table (referrer_id, referred_id, created_at), write a self-join query that finds pairs of people who referred each other (mutual referrals). Discuss what makes this self-join different from a hierarchy self-join, and what indexing you'd want on a large table for this pattern.
Rewrite a per-row correlated scalar subquery (one that runs once per outer row to compute a count or sum) into an equivalent JOIN with an aggregation, and explain why the rewritten version is usually faster on large tables.
Given three tables joined as A LEFT JOIN B LEFT JOIN C, explain how changing the order in which the outer joins are evaluated can change which rows survive in the final result, not just how fast the query runs. Construct a small example that demonstrates it, and show how you'd restructure the query (e.g. via a derived table or CTE) to get the semantics you actually want.
Given employees(employee_id, name, dept_id) and departments(dept_id, dept_name), write a query that returns each employee's name and their department name, but only for employees who currently have a department assigned. Explain why the join you chose is the right one, and what happens to employees with no department.
Given an employees table that references itself for a manager relationship (employee_id, name, manager_id), write a query that returns each employee alongside their manager's name, showing NULL (or an explicit 'no manager') for anyone at the top of the org. Explain why a self-join is the natural tool here, and how you'd extend the same pattern one more level up (manager's manager) or decide you need a recursive CTE instead.
Unlock Full Question Bank
Get access to all 35 SQL Joins and Set Operations interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.