Interview Q&A · SQL · 14 questions in this topic

JOINs In Depth — SQL Interview Q&A

All SQL topics

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

Example.sqlsql
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

  1. 1INNER — matches only.
  2. 2LEFT — all left rows, NULLs for misses.
  3. 3FULL — all rows both sides, NULLs for misses.

Example

Example.sqlsql
-- 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

Example.sqlsql
-- 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';

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits