0
0
SQLquery~5 mins

Covering index concept in SQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Covering index concept
O(n)
Understanding Time Complexity

When we use a covering index in a database query, it can change how fast the query runs.

We want to see how the number of steps grows as the data gets bigger when using a covering index.

Scenario Under Consideration

Analyze the time complexity of this SQL query using a covering index.


SELECT order_id, order_date, customer_id
FROM orders
WHERE customer_id = 12345;
-- Assume a covering index exists on (customer_id, order_id, order_date)

This query fetches orders for one customer using a covering index that includes all needed columns.

Identify Repeating Operations

Look for repeated steps in the query execution.

  • Primary operation: Scanning the index entries for the matching customer_id.
  • How many times: Once for each matching order for that customer.
How Execution Grows With Input

As the number of orders for the customer grows, the work grows too.

Input Size (n)Approx. Operations
10About 10 index entries scanned
100About 100 index entries scanned
1000About 1000 index entries scanned

Pattern observation: The work grows directly with the number of matching rows.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the query grows in a straight line with the number of matching orders.

Common Mistake

[X] Wrong: "Using a covering index makes the query run in constant time no matter how many rows match."

[OK] Correct: Even with a covering index, the database must still look at each matching row, so time grows with the number of matches.

Interview Connect

Understanding how covering indexes affect query speed helps you explain real database performance in simple terms.

Self-Check

What if the query requested columns not included in the covering index? How would the time complexity change?