0
0
PHPprogramming~5 mins

Executing queries with query method in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Executing queries with query method
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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

As the number of users grows, the time to fetch and print each user grows too.

Input Size (n)Approx. Operations
10About 10 fetch and print steps
100About 100 fetch and print steps
1000About 1000 fetch and print steps

Pattern observation: The work grows directly with the number of rows; doubling rows doubles work.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how query execution time grows helps you write efficient database code and explain your reasoning clearly in interviews.

Self-Check

"What if we used a query with a WHERE clause that limits results to a fixed number? How would the time complexity change?"