Indexing for Joins: The #1 Speedup
Welcome to **Day 90**. We've mastered Joins (Phase 3). Now, let's make them fast.
The Join Bottleneck
When you join `orders` and `customers` on `customer_id`, the database has to find the matching customer for every single order.
If you have 1 million orders and **no index** on `customers.id`, the database has to do a table scan for every... single... join.
The Foreign Key Rule
Rule of Thumb: **Always index your Foreign Keys.**
-- This column is used for joins, so it MUST be indexed!
CREATE INDEX idx_orders_customer_id ON orders (customer_id);
Why it's often forgotten
Most databases automatically index **Primary Keys** (ID). But they **do not** automatically index Foreign Keys. Many developers assume it's "taken care of," only to find their app lagging as it grows.
Your Task for Today
Check your `orders` table (or similar). Is there an index on the `user_id` or `customer_id` column?
*Day 91: Partial Indexes—Saving Space and Speed.*