4.5 Hours

5. Relational Architecture: Joins & Set Operations

Architecture

Stitching the Web of Data

In a normalized database, your data is split across many tables. To answer a question like Which users bought the Blue Laptop?, you must perform a JOIN. Understanding how the Postgres engine actually performs these joins is the key to writing queries that scale.

The Join Ecosystem

INNER JOIN

The Intersection. Returns only rows where there is a match in BOTH tables. If an order has no user_id, it is excluded.

LEFT JOIN

The Inclusion. Returns ALL rows from the left table. If no match exists on the right, it fills with NULLs. (Great for Users with 0 posts).

FULL OUTER JOIN

The Union. Returns all rows from both tables, matching where possible. Rare but useful for data reconciliation.

Many-to-Many (The Junction Table)

Consider Books and Authors. One book has many authors; one author has many books. You cannot put a Foreign Key on either table. You need a Junction Table (or Bridge Table).

SQL
-- Junction Table Pattern
CREATE TABLE book_authors (
  book_id INT REFERENCES books(id) ON DELETE CASCADE,
  author_id INT REFERENCES authors(id) ON DELETE CASCADE,
  PRIMARY KEY (book_id, author_id) -- Ensures uniqueness!
);
Security Note: Always use ON DELETE CASCADE for junction tables so you don't end up with Ghost' links when an author or book is deleted.

MVCC & Join Performance

When you join two tables, Postgres doesn't just loop through them. It chooses one of three algorithms:

  • Nested Loop: For small tables. It iterates through every row of A and checks B.
  • Hash Join: For medium tables. It builds a Hash Map of table A in RAM and then scans B once.
  • Merge Join: For massive tables that are already sorted by the Join Key.

The Planner's Choice

Postgres uses statistics (from ANALYZE) to decide which algorithm is cheapest. This is why keeping your database statistics up-to-date is vital for Join speed.

Step-by-Step: Writing a Multi-Table Join

  1. Define the Target: What do you want to see? (e.g., User Name and Order Total).
  2. Identify the Chain: users -> orders -> order_items.
  3. Aliasing: Use short names (u, o, oi) to make the query readable.
  4. Joining: Link them using the ON clause (u.id = o.user_id).

Knowledge Check

Ready to test your understanding of 5. Relational Architecture: Joins & Set Operations?

Back