Covering index concept in SQL - Time & Space 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.
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.
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.
As the number of orders for the customer grows, the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 index entries scanned |
| 100 | About 100 index entries scanned |
| 1000 | About 1000 index entries scanned |
Pattern observation: The work grows directly with the number of matching rows.
Time Complexity: O(n)
This means the time to run the query grows in a straight line with the number of matching orders.
[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.
Understanding how covering indexes affect query speed helps you explain real database performance in simple terms.
What if the query requested columns not included in the covering index? How would the time complexity change?