Why table design matters in SQL - Performance Analysis
Good table design affects how fast database queries run. We want to see how the structure of tables changes the work needed to get data.
How does the way we build tables impact the speed of data retrieval?
Analyze the time complexity of this simple query on two different table designs.
-- Query to find all orders for a customer
SELECT * FROM Orders WHERE CustomerID = 123;
-- Table design 1: Orders with CustomerID indexed
-- Table design 2: Orders without index on CustomerID
This query fetches all orders for one customer. The difference is whether CustomerID is indexed or not.
Look at what the database does repeatedly to answer the query.
- Primary operation: Searching rows in the Orders table for matching CustomerID.
- How many times: Once per row in the table if no index; fewer times if an index is used.
Think about how the work changes as the number of orders grows.
| Input Size (n) | Approx. Operations Without Index |
|---|---|
| 10 | 10 row checks |
| 100 | 100 row checks |
| 1000 | 1000 row checks |
Pattern observation: Without an index, the database checks every row, so work grows directly with table size.
Time Complexity: O(n)
This means the time to find orders grows in direct proportion to how many orders there are.
[X] Wrong: "Adding more columns to a table always slows down queries significantly."
[OK] Correct: The main factor is how the table is organized and indexed, not just the number of columns.
Understanding how table design affects query speed shows you know how to build databases that work well as they grow. This skill helps you write faster queries and design better systems.
"What if we added an index on CustomerID? How would the time complexity change when searching for orders?"