Skip to content

Joins

Combine tables with inner and outer joins, and check that the join does not multiply your rows.

Practise: 26 questions

When you need it

You need a join whenever the columns you want live in more than one table: customer names next to orders, plan prices next to subscriptions. Words that signal it: "with their", "along with", "for each customer", "including those with none".

The second half of the skill is knowing what the join does to the row count. Interviewers care more about that than about syntax.

The shape of the query

select a.col, b.col
from a
join b on b.a_id = a.id          -- keeps only matching rows
left join c on c.a_id = a.id     -- keeps every row of a, NULLs when no match
where <filter on a>;

Step by step:

  1. Pick the table that sets the grain. If the answer is one row per customer, start from customers.
  2. Join the other tables on their keys. Name the key relationship in your head: one customer to many orders.
  3. Use INNER JOIN when a missing match means the row should disappear. Use LEFT JOIN when the left row must survive.
  4. Check the row count before and after.
select c.country,
       count(distinct c.customer_id) as customers,
       count(o.order_id) as orders
from customers c
left join orders o
  on o.customer_id = c.customer_id
 and o.status = 'completed'
group by c.country
order by c.country;

Every customer is kept, even those with no completed orders. The status test sits in the ON clause on purpose. Moved to WHERE, it would delete the unmatched rows and turn the left join back into an inner join.

A join across three tables, summing units per product name:

select p.product_name, sum(oi.quantity) as units
from order_items oi
join orders o on o.order_id = oi.order_id
join products p on p.product_id = oi.product_id
where o.status = 'completed'
group by p.product_name
order by units desc, p.product_name
limit 5;

Traps interviewers look for

Variations

In other warehouses

Practise joins