How GROUP BY changes query execution in SQL - Performance & Efficiency
Start learning this pattern below
Jump into concepts and practice - no test required
When we use GROUP BY in SQL, the database groups rows before doing calculations.
We want to know how this grouping affects the time it takes to run the query.
Analyze the time complexity of the following code snippet.
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
This query counts how many employees are in each department by grouping rows by department.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all employee rows and grouping them by department.
- How many times: Each row is visited once, then grouped into a bucket for its department.
As the number of employees grows, the database must process more rows and assign each to a group.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row checks and group assignments |
| 100 | About 100 row checks and group assignments |
| 1000 | About 1000 row checks and group assignments |
Pattern observation: The work grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to run the query grows roughly in a straight line with the number of rows.
[X] Wrong: "GROUP BY makes the query take much longer than just scanning rows because it does extra work for each group."
[OK] Correct: Grouping adds some work, but the main cost is still reading each row once. The grouping step is efficient and scales linearly with input size.
Understanding how GROUP BY affects query time helps you explain how databases handle data summarization efficiently.
"What if we added an ORDER BY after GROUP BY? How would the time complexity change?"
Practice
GROUP BY clause do in an SQL query?Solution
Step 1: Understand the purpose of GROUP BY
The GROUP BY clause collects rows with the same values in specified columns into groups.Step 2: Compare with other SQL clauses
Sorting is done by ORDER BY, filtering by WHERE, and removing duplicates by DISTINCT, not GROUP BY.Final Answer:
It groups rows that have the same values in specified columns. -> Option BQuick Check:
GROUP BY groups rows by column values [OK]
- Confusing GROUP BY with ORDER BY
- Thinking GROUP BY filters rows
- Assuming GROUP BY removes duplicates
department?Solution
Step 1: Identify correct GROUP BY usage
The GROUP BY clause must follow the FROM clause and specify the column to group by, here 'department'.Step 2: Check each option's syntax
SELECT department, COUNT(*) FROM employees GROUP BY department; uses GROUP BY correctly. SELECT department, COUNT(*) FROM employees ORDER BY department; uses ORDER BY which sorts, not groups. SELECT department, COUNT(*) FROM employees WHERE department; uses WHERE incorrectly. SELECT department, COUNT(*) FROM employees HAVING department; uses HAVING without GROUP BY, which is invalid.Final Answer:
SELECT department, COUNT(*) FROM employees GROUP BY department; -> Option CQuick Check:
GROUP BY syntax: SELECT ... FROM ... GROUP BY column [OK]
- Using ORDER BY instead of GROUP BY
- Using WHERE to group rows
- Using HAVING without GROUP BY
sales with columns region and amount, what is the output of this query?SELECT region, SUM(amount) FROM sales GROUP BY region;
Solution
Step 1: Understand GROUP BY with aggregate functions
The query groups rows by 'region' and calculates the sum of 'amount' for each group.Step 2: Analyze the output
The result shows each region once with the total sales amount summed from all rows in that region.Final Answer:
A list of regions with the total sales amount per region. -> Option AQuick Check:
GROUP BY + SUM() = totals per group [OK]
- Expecting all rows without grouping
- Thinking SUM() causes error with GROUP BY
- Confusing grouping with sorting
SELECT department, employee_name, COUNT(*) FROM employees GROUP BY department;
Solution
Step 1: Check columns in SELECT with GROUP BY
When using GROUP BY on 'department', all selected columns must be grouped or aggregated.Step 2: Identify the error
'employee_name' is neither grouped nor aggregated, causing a syntax error.Final Answer:
You cannot select employee_name without grouping by it or using an aggregate function. -> Option AQuick Check:
Non-grouped columns must be aggregated [OK]
- Selecting non-grouped columns without aggregation
- Thinking COUNT(*) is invalid with GROUP BY
- Misplacing GROUP BY clause
Solution
Step 1: Understand HAVING clause usage
HAVING filters groups after aggregation, so it must come after GROUP BY.Step 2: Check query order and syntax
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5; correctly places HAVING after GROUP BY with condition COUNT(*) > 5. Other options misuse HAVING or WHERE clauses.Final Answer:
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5; -> Option DQuick Check:
HAVING filters groups after GROUP BY [OK]
- Using WHERE to filter aggregated results
- Placing HAVING before GROUP BY
- Confusing WHERE and HAVING clauses
