JOIN performance considerations in MySQL - Time & Space Complexity
When we use JOINs in SQL, we combine rows from two or more tables. Understanding how the time to do this grows helps us write faster queries.
We want to know: how does the work increase when tables get bigger?
Analyze the time complexity of the following JOIN query.
SELECT orders.order_id, customers.customer_name
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id;
This query matches each order with its customer by comparing IDs in both tables.
Look for repeated steps in the JOIN process.
- Primary operation: Matching each row in the orders table with rows in the customers table.
- How many times: For each order, the database looks up the matching customer.
Think about what happens as tables grow.
| Input Size (orders x customers) | Approx. Operations |
|---|---|
| 10 x 10 | About 100 checks |
| 100 x 100 | About 10,000 checks |
| 1000 x 1000 | About 1,000,000 checks |
Pattern observation: Without indexes, the work grows very fast, roughly multiplying the sizes of both tables.
Time Complexity: O(n x m)
This means the time to join grows roughly by multiplying the number of rows in both tables.
[X] Wrong: "JOINs always run quickly no matter table size."
[OK] Correct: Without indexes, the database must check many pairs, so bigger tables mean much more work.
Knowing how JOINs scale helps you explain query speed and shows you understand how databases handle data behind the scenes.
What if we added an index on the join column? How would the time complexity change?