Skip to content
Commitwise
Menu
Databases

Joins: inner, outer, self and anti-joins

How JOIN combines tables, why an order with three items comes back three times, LEFT JOIN and the WHERE clause that quietly turns it into an INNER JOIN, finding rows with no match, self-joins for managers and duplicates, and joining on ranges. The join questions of every SQL interview.

beginner

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The orders report shows customer ids, and the manager wants names. The “customers who never ordered” list is empty, though marketing knows they exist. Revenue on the dashboard is exactly twice what the bank says. All three are join problems, and joins are the part of SQL that interviewers test most.

A foreign keyForeign keyA column that points at a row in another table, and that the database keeps valid.Open in glossary → like orders.customer_id stores a link to another table. A join follows those links when you read, so one query can return the order, its customer and its products together. The examples use the shop tables from How relational databases work.

New to some of these? Open what you need, or skip ahead.

Basics:Tables, rows and keys

A table has named, typed columns, and each row is one thing (one customer, one order). The primary keyPrimary keyThe column (or columns) that uniquely identifies each row of a table; never empty, never repeated.Open in glossary → (usually id) identifies each row, and a foreign keyForeign keyA column that points at a row in another table, and that the database keeps valid.Open in glossary → like orders.customer_id points at a row in another table.

Basics:SELECT, WHERE and NULL

SELECT columns FROM table WHERE condition ORDER BY column reads rows; it runs FROM, then WHERE, then SELECT, then ORDER BY. NULL means “no value”: a comparison with it is unknown, so you test it with IS NULL. The SQL basics lesson covers both.

Part Not started

Combining tables with JOIN

orders stores customer_id = 42, but the report needs the customer’s name, which lives in customers. A join puts them side by side:

SELECT o.id, o.created_at, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id;

Read it as: “for each order, find the customer whose id equals the order’s customer_id, and give me columns from both.”

  • orders o gives the table a short nickname, an alias. Then o.id means “the id of orders” and c.id “the id of customers”. Both tables have an id, so without the prefix the database wouldn’t know which you mean.
  • ON says how rows match. It’s almost always “foreign key equals primary key”.
  • JOIN on its own means INNER JOIN: only pairs that match are kept. An order whose customer doesn’t exist (impossible with a foreign key) would be dropped.

You get one row per match. Join orders to their items, and an order with three items comes back as three rows, each repeating the order’s columns. That’s not a bug, it’s what a join is: every combination that satisfies ON.

You can keep joining. Order, then its items, then each item’s product:

SELECT o.id AS order_id, p.name, oi.quantity
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN products p     ON p.id = oi.product_id
WHERE o.id = 1001;

A join is a filtered Cartesian product: every pair of rows for which the ON predicate is true. Things to have ready:

  • Syntax. Explicit JOIN … ON over comma joins (FROM a, b WHERE …), which hide a missing condition as an accidental cross join. USING (col) is fine when names match; avoid NATURAL JOIN, which silently joins on every same-named column (id, created_at).
  • Cardinality. Joining a parent to a one-to-many child repeats the parent per child. Joining it to two independent children (items and payments) produces items × payments rows per order, the “chasm trap”: sum(oi.quantity * oi.unit_price) gets multiplied by the payment count. Aggregate each child first, then join (see below).
  • Algorithms. Nested loop: for each outer row, probe the inner side; great with a small outer side and an index on the inner join column. Hash join: build a hash table on the smaller input, stream the other; best for large equality joins, needs work_mem. Merge join: both inputs sorted on the key (from indexes or a sort). The planner picks by estimated row counts, so bad estimates show up as nested loops over millions of rows.
  • Indexes. Index the foreign key side (order_items.order_id, orders.customer_id); PostgreSQL doesn’t do it for you.
  • ORMs. JOIN FETCH / @EntityGraph in JPA and @Relation in Room are joins (or follow-up queries) under the hood; the N+1 problemN+1 query problemRunning one query for a list and then one more query per item to load its related data.Open in glossary → is the absence of one.

Predict the output

Order 1001 has three items. Order 1002 has no items yet. How many rows does this return?

SELECT o.id, oi.product_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.id IN (1001, 1002);
-- orders with the customer's name and email
SELECT o.id, o.status, o.total, c.name, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= now() - interval '7 days'
ORDER BY o.created_at DESC;

-- everything in one order: product names, quantities, line totals
SELECT p.name, oi.quantity, oi.unit_price, oi.quantity * oi.unit_price AS line_total
FROM order_items oi
JOIN products p ON p.id = oi.product_id
WHERE oi.order_id = 1001
ORDER BY p.name;

Worked example: a join, row by row

Take three tiny tables:

customers.idname
1Ana
2Ben
3Cleo
orders.idcustomer_id
101
111
122

Now run SELECT o.id, c.name FROM orders o JOIN customers c ON c.id = o.customer_id;

  1. Start with order 10. Its customer_id is 1. Which customer has id = 1? Ana. Output: 10, Ana.
  2. Order 11. Also customer 1, so Ana again. Output: 11, Ana. Ana appears twice because she has two orders.
  3. Order 12. Customer 2 is Ben. Output: 12, Ben.
  4. What about Cleo? No order has customer_id = 3, so no pair includes her. An inner join keeps only pairs, and Cleo isn’t in the result at all.

The result has three rows, one per order. If you need Cleo too, with an empty order, that’s a LEFT JOIN, coming next.

Deep diveJoin fan-out: the revenue report that doubledInterview favorite

The finance dashboard sums each day’s order value and payments:

SELECT o.created_at::date AS day,
       sum(oi.quantity * oi.unit_price) AS sold,
       sum(pay.amount)                  AS paid
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN payments pay   ON pay.order_id = o.id
GROUP BY day;

An order with 3 items and 2 payments (a split payment, or a failed attempt and a retry) produces 3 × 2 = 6 rows. sold counts every item twice, paid counts every payment three times. Most orders have one payment, so totals look plausible and the bug survives for months.

The fix is to aggregate each child to one row per order before joining:

WITH items AS (
    SELECT order_id, sum(quantity * unit_price) AS sold
    FROM order_items GROUP BY order_id
), paid AS (
    SELECT order_id, sum(amount) AS paid
    FROM payments GROUP BY order_id
)
SELECT o.created_at::date AS day, sum(i.sold) AS sold, sum(p.paid) AS paid
FROM orders o
JOIN items i     ON i.order_id = o.id
LEFT JOIN paid p ON p.order_id = o.id
GROUP BY day;

How to spot it in review: two one-to-many joins from the same parent plus an aggregate, or a DISTINCT / count(DISTINCT …) added “to fix duplicates”. Ask what the grain of the result is (one row per what?) and check that every join keeps it. When you only need to know whether a child exists, use EXISTS, which never multiplies rows.

  • JOIN … ON = filtered Cartesian product; inner join drops unmatched rows. Avoid comma joins and NATURAL JOIN.
  • One row per match: parent repeats per child. Two independent one-to-many joins multiply (chasm trap): aggregate children first, or use EXISTS.
  • Nested loop (small outer, indexed inner), hash join (large equality), merge join (sorted). Index FK columns.
  • Know the grain of every result before adding sum, count or DISTINCT.
SELECT o.id, c.name, i.sold
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN (SELECT order_id, sum(quantity * unit_price) AS sold
      FROM order_items GROUP BY order_id) i ON i.order_id = o.id
WHERE EXISTS (SELECT 1 FROM payments p WHERE p.order_id = o.id);

Check this part

  1. What does ON c.id = o.customer_id do in a join?

  2. A customer has no orders. Is she in the result of customers JOIN orders?

  3. An order has 3 items and 2 payments. Joining orders to both and summing item values counts each item how many times?

  4. When does the planner usually prefer a hash join?

JOIN … ON pairs every row with the rows it matches; an inner join drops rows without a match. You get one row per match, so an order with three items appears three times. Use table aliases and prefix columns. Joining two independent one-to-many tables multiplies rows and breaks sums.

Part Not started

LEFT JOIN and the rows with no match

An inner join drops customers without orders. Often that’s exactly the row you care about: “customers who signed up but never bought anything”.

A LEFT JOIN keeps every row of the left table (the one before LEFT JOIN). When a row has a match, you get the pair, as before. When it has none, you still get the row once, and the right table’s columns are NULL:

SELECT c.name, o.id AS order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;
nameorder_id
Ana10
Ana11
Ben12
CleoNULL

To keep only the customers without orders, keep the rows where the right side is empty. This is called an anti-join:

SELECT c.id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

The other joins, briefly:

JoinKeeps
JOIN (inner)only matching pairs
LEFT JOINevery left row, matched or not
RIGHT JOINevery right row; just a LEFT JOIN with the tables swapped, so most people never use it
FULL JOINevery row from both sides
CROSS JOINevery combination, no ON: 3 sizes × 4 colors = 12 variants

The rule that explains most outer-join bugs: ON decides which rows match; WHERE filters the result afterwards. For an inner join it makes no difference where a condition goes. For a LEFT JOIN, a condition on the right table in WHERE removes exactly the NULL-extended rows the left join was supposed to keep, turning it into an inner join. Put right-table conditions in ON; put left-table conditions in WHERE.

Patterns:

  • Anti-join (“rows with no match”): NOT EXISTS (SELECT 1 FROM … WHERE …) is the clearest and NULL-safe; LEFT JOIN … WHERE right.pk IS NULL is equivalent (test a non-nullable column, usually the primary key). Avoid NOT IN (subquery) on nullable columns. PostgreSQL plans NOT EXISTS and the LEFT JOIN form as the same Hash Anti Join.
  • Semi-join (“rows with at least one match”): EXISTS, or IN (subquery). Joining and adding DISTINCT does the same thing more expensively and hides fan-out.
  • Counting with LEFT JOIN: count(o.id), not count(*), or customers without orders count as 1.
  • Chains: after a LEFT JOIN, a following inner JOIN that uses the right table’s columns drops the NULL rows again. Make the rest of the chain left joins too, or join it inside parentheses/a subquery.
  • FULL JOIN is for reconciliation: “rows in our ledger vs rows in the provider’s report”, with COALESCE(a.id, b.id).
  • LATERAL (PostgreSQL, MySQL 8.0.14+; CROSS/OUTER APPLY in SQL Server) lets the right side refer to the left row, e.g. “each customer’s latest order” (below).

Predict the output

The goal: every customer, with their 2026 orders if they have any. Cleo has only orders from 2025. Is Cleo in the result?

SELECT c.name, o.id, o.created_at
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= date '2026-01-01';
-- every customer and how many orders they have, including 0
SELECT c.id, c.name, count(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name;

-- products nobody has ever ordered
SELECT p.id, p.name
FROM products p
WHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.id);

-- every size and color combination, to create variants
SELECT s.label AS size, col.name AS color
FROM sizes s
CROSS JOIN colors col;

The list that’s always empty

Spot the bugCustomers who never ordered

Tap the line with the bug.

-- marketing wants to email everyone who signed up but never ordered
SELECT c.id, c.email
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

Deep diveLATERAL: each customer's latest orderInterview favorite

“Show each customer with their most recent order” is a classic. With LATERAL, the subquery runs per customer and can use c.id:

SELECT c.id, c.name, last.id AS order_id, last.created_at
FROM customers c
LEFT JOIN LATERAL (
    SELECT o.id, o.created_at
    FROM orders o
    WHERE o.customer_id = c.id
    ORDER BY o.created_at DESC, o.id DESC
    LIMIT 1
) last ON true;

With an index on orders (customer_id, created_at DESC, id DESC), each probe reads one index entry, so this is fast when you show a page of customers. LEFT JOIN … ON true keeps customers without orders; CROSS JOIN LATERAL would drop them. Change LIMIT 1 to LIMIT 3 for “the last three orders per customer”.

Alternatives an interviewer may expect you to compare:

  • Window function: row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) and keep row 1. One pass over all orders; better when you need the answer for every customer at once (see the Window functions lesson).
  • PostgreSQL DISTINCT ON (customer_id) with a matching ORDER BY: concise, PostgreSQL-only.
  • Correlated max(created_at) subquery: returns several rows when two orders share the timestamp, unless you add a tiebreaker.
  • ON decides matches, WHERE filters afterwards: a right-table condition in WHERE turns LEFT JOIN into inner. Put it in ON.
  • Anti-join: NOT EXISTS (or LEFT JOIN … WHERE right.pk IS NULL), never NOT IN on nullable columns. Semi-join: EXISTS, not JOIN + DISTINCT.
  • count(right.id) with left joins; keep the rest of the chain left.
  • FULL JOIN for reconciliation, CROSS JOIN for combinations, LATERAL for top-N per row.

Check this part

  1. What does LEFT JOIN give for a customer with no orders?

  2. How do you list products that have never been ordered?

  3. Where should o.status = 'PAID' go to keep customers without paid orders in a LEFT JOIN?

  4. Customers LEFT JOIN orders, then GROUP BY customer with count(*). What does a customer with no orders get?

LEFT JOIN keeps every row of the left table and fills NULLs where nothing matches. A WHERE condition on the right table turns it back into an inner join; put it in ON. Rows with no match: LEFT JOIN … IS NULL or NOT EXISTS. RIGHT, FULL and CROSS joins exist but are rarer.

Part Not started

Self-joins and joins on ranges

Sometimes the link points into the same table. Every employee has a manager, and the manager is an employee too:

employees.idnamemanager_idsalary
1MajaNULL9000
2Luka16000
3Sara19500

To show each employee with their manager’s name, join employees to itself. Give it two aliases, as if there were two copies of the table: e for the employee and m for the manager.

SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;

It’s a LEFT JOIN so that Maja, who has no manager, still appears, with NULL as her manager.

A self-join also compares rows with each other, for example to find products with the same name. To get each pair once, and never a product paired with itself, join on p1.id < p2.id:

SELECT p1.id, p2.id, p1.name
FROM products p1
JOIN products p2 ON p2.name = p1.name AND p1.id < p2.id;

ON doesn’t have to be “equals”. Any condition works. A shipping table that says “orders between 0 and 50 cost 5, between 50 and 100 cost 3” joins on a range:

SELECT o.id, o.total, s.fee
FROM orders o
JOIN shipping_fees s ON o.total >= s.min_total AND o.total < s.max_total;
  • Self-joins are ordinary joins with two aliases. For pairs, a.id < b.id removes both self-pairs and mirror duplicates; <> returns each pair twice.
  • Hierarchies. One self-join is one level. Arbitrary depth (all reports under a manager, category trees, threaded comments) needs WITH RECURSIVE (the CTE lesson), or a different model: materialized path (/1/4/9/), nested sets, closure tables, PostgreSQL ltree.
  • Non-equi joins (<, BETWEEN, overlaps) can’t use hash joins; they run as nested loops, ideally with an index (B-tree on the range start, GiST on range types). Shipping bands, tax rates by date, sessionizing events and “events within 5 minutes of each other” are typical.
  • Temporal joins: “the price that was valid when the order was placed” joins on valid_from <= t AND t < valid_to. Half-open intervals avoid double matches on the boundary; overlapping rows are the real risk (below).
  • Window functions often replace self-joins: “difference from the previous row” was JOIN t2 ON t2.seq = t1.seq - 1, now lag(); “rows above the group average” was a join to an aggregated copy, now avg() OVER (PARTITION BY …). One pass instead of two.
  • Interview classics: employees earning more than their manager, duplicate rows (a.id < b.id), consecutive days (b.day = a.day + 1), mutual follows (f1.a = f2.b AND f1.b = f2.a).

Predict the output

Three products are called 'Mug' (ids 4, 7 and 9). How many rows does this return?

SELECT p1.id, p2.id
FROM products p1
JOIN products p2 ON p2.name = p1.name AND p1.id <> p2.id
WHERE p1.name = 'Mug';
-- each employee with their manager (NULL for the top)
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;

-- duplicate customers: the same email in different letter case
SELECT a.id, b.id, a.email
FROM customers a
JOIN customers b ON lower(b.email) = lower(a.email) AND a.id < b.id;

Practice: a classic interview question

Exerciseeasy

Employees who earn more than their managers

Using the employees table above (id, name, manager_id, salary), return the names of employees who earn more than their own manager. With the sample data, the answer is Sara.

›

You need the employee’s salary and the manager’s salary in the same row. Two aliases of the same table.

›

Maja has no manager. Should she be compared at all? Which join drops her?

SolutionTry it yourself first
SELECT e.name
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;

An inner join is right here: an employee without a manager has nobody to out-earn, so dropping Maja is correct. For Sara the joined row has e.salary = 9500 and m.salary = 9000 (Maja’s), so she passes; Luka’s 6000 doesn’t.

Deep divePrice at the time of the order: joining on a rangeInterview favorite

A price_history table keeps every price a product ever had:

CREATE TABLE price_history (
    product_id bigint NOT NULL REFERENCES products (id),
    price      numeric(10, 2) NOT NULL,
    valid_from timestamptz NOT NULL,
    valid_to   timestamptz             -- NULL = still valid
);

SELECT o.id, oi.product_id, ph.price
FROM orders o
JOIN order_items oi  ON oi.order_id = o.id
JOIN price_history ph ON ph.product_id = oi.product_id
                     AND ph.valid_from <= o.created_at
                     AND (ph.valid_to IS NULL OR o.created_at < ph.valid_to);

Half-open intervals (from <= t < to) make consecutive periods meet without overlapping: a timestamp exactly at the change matches only the new price. Using BETWEEN (both ends inclusive) would match two rows at the boundary and duplicate the order line.

The real production bug is overlapping rows: a back-office import adds a new price without closing the old one, and orders in the overlap appear twice, doubling revenue in every report that joins this table. Let the database forbid it. PostgreSQL can, with a range column and an exclusion constraint:

CREATE EXTENSION IF NOT EXISTS btree_gist;

ALTER TABLE price_history
    ADD COLUMN valid_during tstzrange
        GENERATED ALWAYS AS (tstzrange(valid_from, valid_to, '[)')) STORED,
    ADD CONSTRAINT no_overlapping_prices
        EXCLUDE USING gist (product_id WITH =, valid_during WITH &&);

Now two rows for the same product with overlapping periods are rejected at insert time, and the join can use o.created_at <@ ph.valid_during with the GiST index. PostgreSQL 18 also supports WITHOUT OVERLAPS in primary keys and unique constraints for the same purpose. In interviews, the point to make is that “copy unit_price into order_items” (from the first lesson) avoids this join entirely for the most common question, and the history table serves analytics.

  • Self-join = two aliases; a.id < b.id for unique pairs. One join per level; arbitrary depth needs WITH RECURSIVE or path/closure models.
  • Non-equi joins (ranges, overlaps) run as nested loops: index the range or use range types with GiST.
  • Temporal joins: half-open [from, to) intervals; prevent overlaps with an exclusion constraint (or PostgreSQL 18 WITHOUT OVERLAPS).
  • Many old self-joins are window functions now: lag(), avg() OVER (PARTITION BY …).

Check this part

  1. Why does a self-join need two aliases?

  2. Which condition returns each pair of duplicate products once?

  3. Why use valid_from <= t AND t < valid_to instead of BETWEEN for price periods?

  4. How do you return all employees under a manager, at any depth?

A self-join joins a table to itself under two aliases: employees to their managers, or rows to similar rows. Use a < b to get each pair once. ON can use any condition, not just equality: ranges, like a price valid between two dates. Deeper hierarchies need a recursive CTE.

Key takeaways

  • A join pairs rows using ON, usually foreign key = primary key. Alias tables and prefix columns.
  • An inner JOIN keeps only matches and returns one row per match, so a parent repeats per child.
  • LEFT JOIN keeps every left row, with NULLs where nothing matched. Rows with no match: LEFT JOIN … WHERE right.id IS NULL or NOT EXISTS.
  • A self-join uses two aliases of one table; a.id < b.id gives each pair once.
  • ON can use ranges, not just equality.
  • Know the grain: two one-to-many joins multiply rows; aggregate children first or use EXISTS.
  • Right-table filters in ON, not WHERE, for outer joins; count(right.id); NOT EXISTS over NOT IN.
  • Join algorithms follow row estimates; index foreign keys; LATERAL for top-N per row.
  • Recursive CTEs for hierarchies, half-open intervals and exclusion constraints for temporal joins, window functions instead of many self-joins.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.