SQL Joins (ANSI)

Context: FIT2094_MOC, FIT3003_MOC · combine rows across tables on a PK–FK match · SQL form of the relational-algebra join · ANSI syntax required in FIT2094; FIT3003 lectures and labs use the old-style form Problem it solves: retrieve columns from two related tables, matching each child row to its parent.

Quick Revision

  • 🎯 Trigger: data spans two tables ➔ JOIN … ON (explicit condition); shortcut to USING/NATURAL only when key names match.
  • ⚡ Key Constraint: a NATURAL JOIN on tables with no common column silently becomes a Cartesian product, not a join — as does an old-style join with a missing WHERE condition.

🔧 Minimal Working Example

SELECT *
FROM   drone.manufacturer
JOIN   drone.drone_type
ON     manufacturer.manuf_id = drone_type.manuf_id;

Expected output: manufacturers matched to their drone types; the result has two manuf_id columns (one per table).

  • JOIN … ON ➔ most flexible/reliable; state the equi-join condition explicitly; works even when key columns are named differently; keeps both columns (duplicate).
  • Prefix duplicates ➔ with duplicate names you must qualify: manufacturer.manuf_id.
  • JOIN … USING (col) ➔ when both tables share the column name; removes the duplicate column.
  • NATURAL JOIN ➔ no condition; auto-joins on all same-named columns and drops duplicates.

🔀 Variations

FormConditionDuplicate col?Requires
JOIN … ONexplicit ON a=bkept (qualify)nothing (any names)
JOIN … USINGUSING (col)removedsame column name
NATURAL JOINimplicit (all common names)removedsame column name(s)
old-style / implicitjoin condition in WHEREkept (qualify)one condition per table pair

🔹 Old-style (implicit) join — FIT3003 house syntax

✍️ Practice

⚠️ Common Mistakes

  • 💡 Unit-specific syntax rule ➔ implicit joins are banned in FIT2094 (marked wrong in all assessments) but taught and used in FIT3003 — match the syntax to the unit assessing you.
  • 💡 NATURAL JOIN with no shared column = Cartesian product ➔ every row paired with every row; prefer explicit JOIN … ON when unsure.
  • 💡 INNER drops unmatched rows ➔ to keep a table’s rows with no match (or join a table to itself), see SQL Self Join and Outer Join.