Skip to the page

Joining and aggregating · core

JOINs: inner, left, right, full, self

INNER JOIN keeps only matching pairs, LEFT JOIN keeps every row from the left table and fills NULLs when there is no match, and a filter on the right table belongs in the ON clause of a LEFT JOIN, because in WHERE it silently turns it back into an inner join.

The notes

What you must know

  • INNER: rows with a match on both sides. LEFT (OUTER): all left rows, right columns NULL when no match. RIGHT: the mirror (rarely used). FULL: all rows from both. CROSS: every combination.
  • Join conditions usually follow foreign keys: orders.user_id = users.id. Index the foreign key columns.
  • Filter on the right table of a LEFT JOIN in ON (LEFT JOIN orders o ON o.user_id = u.id AND o.status = 'paid'); in WHERE it removes the NULL rows.
  • Anti-join (rows with no match): LEFT JOIN ... WHERE right.id IS NULL, or NOT EXISTS.
  • Self-join: join a table to itself with aliases (employee -> manager, users referred by users).
  • Fan-out: joining one row to many multiplies rows; SUMs over the 'one' side then double count. Aggregate before joining, or use subqueries.
  • Joining three tables: chain the joins; think about which side may be missing to choose INNER vs LEFT.

The red pen

Common traps: mistake → fix

  • Mistake: LEFT JOIN with WHERE right.col = 'x' still keeps all left rows

    Fix: WHERE drops the NULL rows, so it behaves like an INNER JOIN.

  • Mistake: A join never changes row counts

    Fix: one-to-many joins multiply rows and inflate SUM/COUNT.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain INNER vs LEFT vs FULL JOIN with an example.
  2. Find customers who never placed an order.
  3. Why did adding a join double my revenue total?
  4. Write a self-join to show each employee with their manager's name.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview