4.4.6 · D3Databases

Worked examples — Joins — INNER, LEFT, RIGHT, FULL OUTER, CROSS, SELF

2,877 words13 min readBack to topic

This page is the drill hall for the parent Joins topic. The parent taught you the one question"when a row has no match, what do I do with it?" Here we walk every case that question can throw at you, one worked example per cell, so you never meet a join scenario you haven't already seen solved.

We reuse the parent's tables. Keep them in view:

Employees

emp_id name dept_id manager_id
1 Asha 10 NULL
2 Bilal 20 1
3 Cara NULL 1

Departments

dept_id dept_name
10 Sales
30 Legal

The scenario matrix

Before solving, we list every case-class a join question can be. Each later example is tagged with the cell it covers. If a cell has no example, you'd have a hole — there are none.

# Case class What makes it tricky Covered by
C1 Clean match only (INNER) the "happy path", overlap only Ex 1
C2 Keep-left, pad NULL (LEFT) unmatched left rows survive Ex 2
C3 Anti-join (LEFT + IS NULL) isolate the unmatched side Ex 3
C4 Keep-right / orphan parent direction flip, RIGHT ≡ LEFT swapped Ex 4
C5 Keep-both (FULL OUTER) union of both sides, double padding Ex 5
C6 NULL key degeneracy NULL = NULL is not true Ex 6
C7 Cartesian / no condition (CROSS) size = , real-world grid Ex 7
C8 SELF join + dedup inequality one table, two roles, avoid double/self pairs Ex 8
C9 ON-vs-WHERE trap (limiting behaviour) filter before vs after padding Ex 9
C10 Exam twist: count without running it reason from the derivation formula Ex 10

Ex 1 — Cell C1: the clean match (INNER)


Ex 2 — Cell C2: keep every employee (LEFT + padding)


Ex 3 — Cell C3: the anti-join (find who has NO department)


Ex 4 — Cell C4: keep every department (RIGHT, and the LEFT rewrite)


Ex 5 — Cell C5: keep everyone (FULL OUTER)

The four join outcomes as regions of a Venn picture:

Figure — Joins — INNER, LEFT, RIGHT, FULL OUTER, CROSS, SELF

Ex 6 — Cell C6: the NULL-key degeneracy


Ex 7 — Cell C7: real-world CROSS (build a grid)

Figure — Joins — INNER, LEFT, RIGHT, FULL OUTER, CROSS, SELF

Ex 8 — Cell C8: SELF join with de-duplication


Ex 9 — Cell C9: ON vs WHERE (the limiting/degrade trap)


Ex 10 — Cell C10: exam twist — count without running it


Wrap-up: the matrix is complete

Recall Which cell did each example cover?

C1 INNER ::: Ex 1 C2 LEFT + padding ::: Ex 2 C3 anti-join (IS NULL) ::: Ex 3 C4 RIGHT / orphan parent ::: Ex 4 C5 FULL OUTER union ::: Ex 5 C6 NULL-key degeneracy ::: Ex 6 C7 CROSS grid, size m×n ::: Ex 7 C8 SELF join + dedup ::: Ex 8 C9 ON-vs-WHERE trap ::: Ex 9 C10 count from the formula ::: Ex 10

Back to the parent topic · related: Normalization, Foreign Keys, NULL semantics in SQL, Relational Algebra.