One-to-many relationship design in SQL - Time & Space Complexity
When working with one-to-many relationships in databases, it's important to understand how query time grows as data increases.
We want to know how the time to get related data changes when there are more records.
Analyze the time complexity of the following SQL query.
SELECT customers.name, orders.order_id
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
WHERE customers.customer_id = 123;
This query finds all orders for one customer by joining the customers and orders tables on their IDs.
Look at what repeats when the query runs.
- Primary operation: Scanning the orders table to find matching orders for the customer.
- How many times: Once for each order that belongs to the customer.
As the number of orders for a customer grows, the query takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 orders | About 10 checks to find orders |
| 100 orders | About 100 checks |
| 1000 orders | About 1000 checks |
Pattern observation: The time grows directly with the number of orders for that customer.
Time Complexity: O(n)
This means the time to get all orders grows in a straight line with how many orders the customer has.
[X] Wrong: "The query time depends on the total number of customers in the database."
[OK] Correct: The query filters by one customer, so only that customer's orders affect time, not all customers.
Understanding how queries scale with data size helps you design efficient databases and write fast queries, a key skill in real projects.
"What if we added an index on orders.customer_id? How would that change the time complexity?"