0
0
SQLquery~5 mins

Why aggregation is needed in SQL - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why aggregation is needed
O(n)
Understanding Time Complexity

We want to understand how the time to run aggregation queries changes as data grows.

How does grouping and summarizing data affect the work the database does?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

This query counts how many employees are in each department by grouping rows.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Scanning each row in the employees table once.
  • How many times: Once per row, to assign it to a group and update the count.
How Execution Grows With Input

As the number of employees grows, the database must look at each employee once.

Input Size (n)Approx. Operations
1010 operations (one per employee)
100100 operations
10001000 operations

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run the aggregation grows in a straight line with the number of rows.

Common Mistake

[X] Wrong: "Aggregation queries are always slow because they do extra work."

[OK] Correct: Aggregation just looks at each row once, so it grows linearly, not slower or faster than scanning the data.

Interview Connect

Understanding how aggregation scales helps you explain query performance clearly and confidently.

Self-Check

"What if we added an ORDER BY after the GROUP BY? How would the time complexity change?"