SQL · Module 7 · Lesson 41 min read

FULL OUTER JOIN & CROSS JOIN

FULL OUTER JOIN

Returns all rows from both tables:

  • matched rows are combined
  • unmatched rows from either side appear with NULLs on the other side

Think: LEFT JOIN + RIGHT JOIN together.

Uses

  • Reconciliation: compare bank transactions with app records — what's missing on either side?
  • Comparing two lists (this month vs last month, plan vs actual)
  • Merging data from two sources

Tip: COALESCE(a.key, b.key) gives one combined key column.

CROSS JOIN – every combination

Pairs every row of table A with every row of table B (the Cartesian product).

  • 6 users × 10 categories = 60 rows
  • No ON condition
  • Same as FROM a, b without a WHERE

Uses

  • Generate a grid: every user × every month (so months with zero spending still appear)
  • Every size × every colour for products
  • Combine with generate_series for calendars

⚠️ Be careful: 10,000 × 10,000 = 100 million rows. An accidental cross join (a forgotten ON or WHERE in the old comma syntax) can freeze a database.

Join types summary

JoinKeeps
INNERmatches only
LEFTall left + matches
RIGHTall right + matches
FULLeverything from both
CROSSevery combination
SELFa table joined to itself (next lesson)

Example

SQL
-- FULL OUTER JOIN: reconcile app expenses with a bank statement
CREATE TEMP TABLE bank_tx (ref TEXT, amount NUMERIC, tx_date DATE);
INSERT INTO bank_tx VALUES
  ('Monthly groceries', 5200, '2026-11-05'),
  ('Bus pass',          1000, '2026-11-08'),
  ('ATM withdrawal',    3000, '2026-11-09');     -- not in the app!

SELECT COALESCE(e.title, b.ref)        AS item,
       e.amount                         AS in_app,
       b.amount                         AS in_bank,
       CASE WHEN e.id IS NULL THEN '⚠️ missing in app'
            WHEN b.ref IS NULL THEN '⚠️ missing in bank'
            ELSE '✅ matched' END       AS status
FROM (SELECT * FROM expenses WHERE user_id = 1 AND spent_on >= '2026-11-01') e
FULL OUTER JOIN bank_tx b
  ON b.ref = e.title AND b.amount = e.amount
ORDER BY status;
-- ATM withdrawal | NULL | 3000 | ⚠️ missing in app
-- Movie tickets  |  900 | NULL | ⚠️ missing in bank
-- Bus pass, Monthly groceries   | ✅ matched

-- CROSS JOIN: every user × every month, so zero months still show
SELECT u.name, m.month, COALESCE(sum(e.amount), 0) AS total
FROM users u
CROSS JOIN (VALUES (DATE '2026-09-01'), (DATE '2026-10-01'), (DATE '2026-11-01')) AS m(month)
LEFT JOIN expenses e
       ON e.user_id = u.id
      AND date_trunc('month', e.spent_on) = m.month
WHERE u.id IN (4, 5)
GROUP BY u.name, m.month
ORDER BY u.name, m.month;
-- Bikash Rai: 2950 / 3450 / 1540, Maya Karki: 0 / 0 / 0

-- How many rows would a cross join produce?
SELECT (SELECT count(*) FROM users) * (SELECT count(*) FROM categories) AS combinations;  -- 60