0
0
SQLquery~5 mins

One-to-many relationship design in SQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: One-to-many relationship design
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of orders for a customer grows, the query takes longer.

Input Size (n)Approx. Operations
10 ordersAbout 10 checks to find orders
100 ordersAbout 100 checks
1000 ordersAbout 1000 checks

Pattern observation: The time grows directly with the number of orders for that customer.

Final Time Complexity

Time Complexity: O(n)

This means the time to get all orders grows in a straight line with how many orders the customer has.

Common Mistake

[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.

Interview Connect

Understanding how queries scale with data size helps you design efficient databases and write fast queries, a key skill in real projects.

Self-Check

"What if we added an index on orders.customer_id? How would that change the time complexity?"