Executing queries with query method in PHP - Time & Space Complexity
When running database queries using the query method, it's important to understand how the time it takes grows as the data or query size grows.
We want to know how the number of operations changes when the input gets bigger.
Analyze the time complexity of the following code snippet.
// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
// Execute a query
$result = $pdo->query('SELECT * FROM users');
// Fetch all rows
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
// Process rows
foreach ($rows as $row) {
echo $row['name'] . "\n";
}
This code runs a SQL query to get all users, fetches all results, and then prints each user's name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all rows returned by the query.
- How many times: Once for each row in the users table.
As the number of users grows, the time to fetch and print each user grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 fetch and print steps |
| 100 | About 100 fetch and print steps |
| 1000 | About 1000 fetch and print steps |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles work.
Time Complexity: O(n)
This means the time to run and process the query grows in a straight line with the number of rows returned.
[X] Wrong: "The query method runs instantly no matter how many rows are returned."
[OK] Correct: Fetching and processing each row takes time, so more rows mean more work and longer time.
Understanding how query execution time grows helps you write efficient database code and explain your reasoning clearly in interviews.
"What if we used a query with a WHERE clause that limits results to a fixed number? How would the time complexity change?"