# Topic 29: INNER JOIN
Relational equi-joins, Cartesian product filtering, multi-table joins, and physical join operators (Nested Loop, Hash, Merge).
1. Definition
An INNER JOIN matches and combines rows from two or more tables based on a join condition, returning only rows where the condition evaluates to TRUE in both tables.
2. Explain Like I'm 5
Think of two puzzle pieces: an INNER JOIN only gives you the pieces that snap together perfectly. If a piece has no match on the other side, it gets tossed out.
3. Animation & Visual Simulation
Interactive Engine TracePhysical Join Engine (Build & Probe Phase)
SELECT u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id;Active InputStep 1: Build Phase (Smaller Table)
Key: id=1 ➔ Alice
Key: id=2 ➔ Bob
The optimizer selects the smaller table (users) and hashes primary keys into memory buckets.
4. Real-World Example
Matching users with their orders.
| id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie (No orders) |
| order_id | user_id | product |
|---|---|---|
| 101 | 1 | Laptop |
| 102 | 2 | Phone |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT u.id, u.name, o.product, o.total_amount FROM users u INNER JOIN orders o ON u.id = o.user_id;
SELECT u.name, o.id AS order_id, p.name AS product_name FROM users u JOIN orders o ON u.id = o.user_id JOIN order_items oi ON o.id = oi.order_id JOIN products p ON oi.product_id = p.id;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Unmatched Rows Discarded | Any row in either table without a corresponding match is excluded. |
| Duplicate Key Multiplication | If a key matches 3 rows in table A and 2 rows in table B, the result contains 3 * 2 = 6 rows. |
| INNER Keyword Optional | JOIN defaults to INNER JOIN if no outer modifier is specified. |
| Physical join operators | Cost-Based Optimizers choose between Nested Loop Join, Hash Join, and Merge Join based on table sizes and indexes. |
| Join associativity and commutativity | INNER JOINs are mathematically associative; the optimizer reorders join sequence to minimize intermediate tuples. |
7. Deep Dive: Physical Join Operators: Hash Join, Merge Join, Nested Loop
The Cost-Based Optimizer chooses among three physical join algorithms: 1) Nested Loop Join (scans table A and probes an index on B), 2) Hash Join (hashes smaller table into RAM and probes with larger table), 3) Merge Join (scans two pre-sorted inputs in lockstep).
-- EXPLAIN output showing physical join choice: EXPLAIN ANALYZE SELECT * FROM users u JOIN orders o ON u.id = o.user_id; -- "Hash Join (cost=2.15..18.40 rows=100 width=64)" -- " Hash Cond: (o.user_id = u.id)"
8. Advantages & Disadvantages
Advantages
- •Extracts strictly related data across normalized relational entities.
- •Highly optimized by Cost-Based Optimizers.
Disadvantages & Trade-offs
- •Omitting the ON join condition accidentally creates a massive Cartesian cross product.
9. Common Interview Questions
Q1.How does the Cost-Based Optimizer choose between Nested Loop, Hash Join, and Merge Join?
1. Nested Loop Join: ideal when the outer table is very small and the inner table has a B-Tree index on the join key (O(N log M)). 2. Hash Join: ideal for large unsorted tables with equality conditions; the smaller table is hashed into RAM (work_mem) and the larger table probes it in O(N + M). 3. Merge Join: ideal when both inputs are already sorted by the join key (via indexes or sort); it steps through both inputs in lockstep in O(N + M) with minimal memory.
Q2.What happens when a Hash Join exceeds available work_mem?
If the hash table built on the smaller relation exceeds work_mem, the engine cannot perform an in-memory hash join. It falls back to a Two-Pass Hybrid Hash Join: it hashes rows into disk batches (partitions) on temporary disk storage and reads them back in multiple passes. This causes heavy disk I/O and query slowdown.
Q3.Why does join order matter to the optimizer if INNER JOIN is mathematically commutative?
While A JOIN B produces the exact same result as B JOIN A, the physical execution cost can differ by orders of magnitude. The optimizer uses dynamic programming to evaluate join order permutations, aiming to join the most selective tables first to dramatically reduce the size of intermediate tuple streams entering subsequent join stages.
Q4.What is a Cartesian Product and how does it happen accidentally in INNER JOINs?
A Cartesian Product occurs when two tables are joined without an ON condition (or an ON condition that always evaluates to TRUE), pairing every row in table A with every row in table B. If table A has 10,000 rows and table B has 10,000 rows, the result is 100,000,000 rows, exploding memory and crashing application servers.
Q5.What is the performance difference between joining on an integer primary key vs a string column?
Joining on integers is vastly faster: 1. Integer comparisons are single CPU assembly instructions, 2. Integers are fixed 4 or 8 bytes, maximizing B-Tree page density and hash table cache locality. Joining on strings requires variable-length byte comparisons, collation lookups, higher memory footprint, and slower hash computation.
10. Interview-Ready Answer
“An INNER JOIN returns rows that satisfy the join predicate in both tables, discarding unmatched records. Database engines execute joins physically using Nested Loop, Hash Join, or Merge Join strategies depending on table sizes and index presence.”
11. Quick Test
Table A has 4 rows; Table B has 5 rows. No rows match the join condition A.id = B.a_id. How many rows does "SELECT * FROM A JOIN B ON A.id = B.a_id" return?