Bird
Raised Fist0
SQLquery~10 mins

GROUP BY with aggregate functions in SQL - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - GROUP BY with aggregate functions
Start with table data
Group rows by column(s)
Apply aggregate functions (SUM, COUNT, AVG, etc.) on each group
Return one row per group with aggregated values
End with grouped result set
The query groups rows by specified columns, then calculates aggregate values for each group, returning one summary row per group.
Execution Sample
SQL
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Counts how many employees are in each department by grouping rows by department.
Execution Table
StepActionGroup formedAggregate calculationOutput row
1Read all rows from employees tableNone yetNone yetNone yet
2Group rows by departmentSales: 3 rows, HR: 2 rows, IT: 2 rowsNone yetNone yet
3Calculate COUNT(*) for Sales groupSalesCOUNT = 3('Sales', 3)
4Calculate COUNT(*) for HR groupHRCOUNT = 2('HR', 2)
5Calculate COUNT(*) for IT groupITCOUNT = 2('IT', 2)
6Return all grouped rows with countsAll groupsAll counts calculated[('Sales', 3), ('HR', 2), ('IT', 2)]
7End of query executionAll groups processedAll aggregates doneFinal result set returned
💡 All groups processed and aggregate counts calculated for each group.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
groupsNone{Sales:3 rows, HR:2 rows, IT:2 rows}{Sales:3}{Sales:3, HR:2}{Sales:3, HR:2, IT:2}{Sales:3, HR:2, IT:2}
aggregatesNoneNone{Sales:3}{Sales:3, HR:2}{Sales:3, HR:2, IT:2}{Sales:3, HR:2, IT:2}
output_rowsNoneNone[('Sales', 3)][('Sales', 3), ('HR', 2)][('Sales', 3), ('HR', 2), ('IT', 2)][('Sales', 3), ('HR', 2), ('IT', 2)]
Key Moments - 3 Insights
Why does the query return fewer rows than the original table?
Because the GROUP BY groups multiple rows into one per group, the output has one row per unique group value, as shown in execution_table rows 3-6.
What happens if we use an aggregate function without GROUP BY?
The aggregate function applies to the whole table as one group, returning a single summary row, unlike the multiple groups shown in the execution_table.
Can we select columns not in GROUP BY or aggregate functions?
No, SQL requires all selected columns to be either grouped or aggregated, otherwise it causes an error. This is why only 'department' and COUNT(*) appear in the example.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the COUNT(*) for the HR group at step 4?
A2
B3
C1
D0
💡 Hint
Check the 'Aggregate calculation' column at step 4 in the execution_table.
At which step does the query return the final grouped result set?
AStep 2
BStep 3
CStep 6
DStep 1
💡 Hint
Look for the step where 'Return all grouped rows with counts' happens in the execution_table.
If the employees table had a new department 'Marketing' with 4 employees, how would the output change?
AThe output would remain the same
BA new group 'Marketing' with COUNT 4 would appear
CThe counts for existing groups would increase
DThe query would fail
💡 Hint
Refer to variable_tracker showing how groups and counts form per department.
Concept Snapshot
GROUP BY groups rows by specified columns.
Aggregate functions (COUNT, SUM, AVG, etc.) calculate summary values per group.
Result returns one row per group with aggregated data.
All selected columns must be grouped or aggregated.
Useful for summarizing data by categories.
Full Transcript
This visual execution trace shows how a SQL query with GROUP BY and aggregate functions works. First, the database reads all rows from the table. Then it groups rows by the specified column, here 'department'. Next, it calculates aggregate values like COUNT for each group. Finally, it returns one row per group with the aggregated results. The execution table tracks each step, showing groups formed and counts calculated. The variable tracker shows how groups and aggregates build up over steps. Key moments clarify common confusions like why output rows are fewer than input rows and the need for grouping or aggregation in SELECT. The quiz tests understanding of counts per group, when results are returned, and how adding data affects output. The snapshot summarizes the concept simply for quick review.

Practice

(1/5)
1. What does the GROUP BY clause do in an SQL query?
easy
A. It deletes duplicate rows from the table.
B. It sorts the rows in ascending order.
C. It groups rows that have the same values in specified columns.
D. It filters rows based on a condition.

Solution

  1. Step 1: Understand the purpose of GROUP BY

    The GROUP BY clause is used to group rows that share the same values in one or more columns.
  2. Step 2: Differentiate from other clauses

    Sorting is done by ORDER BY, filtering by WHERE, and removing duplicates by DISTINCT, not GROUP BY.
  3. Final Answer:

    It groups rows that have the same values in specified columns. -> Option C
  4. Quick Check:

    GROUP BY = groups rows by column values [OK]
Hint: GROUP BY groups rows by column values, not sorting or filtering [OK]
Common Mistakes:
  • Confusing GROUP BY with ORDER BY
  • Thinking GROUP BY filters rows
  • Assuming GROUP BY removes duplicates
2. Which of the following SQL queries correctly uses GROUP BY to count employees per department?
easy
A. SELECT department, COUNT(*) FROM employees GROUP BY.;
B. SELECT department, COUNT(*) FROM employees GROUP BY department.;
C. SELECT department, COUNT(*) FROM employees WHERE department GROUP BY.;
D. SELECT department, COUNT(*) FROM employees.;

Solution

  1. Step 1: Check the syntax of GROUP BY usage

    The correct syntax requires specifying the column after GROUP BY and using aggregate functions properly.
  2. Step 2: Analyze each option

    Only SELECT department, COUNT(*) FROM employees GROUP BY department; correctly groups by department and counts employees. The other options have syntax errors: missing column after GROUP BY, no GROUP BY clause, or invalid WHERE syntax.
  3. Final Answer:

    SELECT department, COUNT(*) FROM employees GROUP BY department; -> Option B
  4. Quick Check:

    GROUP BY column + aggregate function = correct syntax [OK]
Hint: GROUP BY must be followed by column names, aggregate functions used outside [OK]
Common Mistakes:
  • Omitting column after GROUP BY
  • Using WHERE incorrectly with GROUP BY
  • Missing aggregate function with GROUP BY
3. Given the table sales with columns region and amount, what is the result of this query?
SELECT region, SUM(amount) FROM sales GROUP BY region;
medium
A. A list of all sales amounts without grouping.
B. A list of regions with the average sales amount.
C. An error because SUM() cannot be used with GROUP BY.
D. A list of regions with the total sales amount for each region.

Solution

  1. Step 1: Understand the query components

    The query groups rows by region and calculates the sum of amount for each group.
  2. Step 2: Determine the output

    The output will show each region once with the total sales amount summed up.
  3. Final Answer:

    A list of regions with the total sales amount for each region. -> Option D
  4. Quick Check:

    GROUP BY region + SUM(amount) = total per region [OK]
Hint: SUM with GROUP BY gives total per group, not average or error [OK]
Common Mistakes:
  • Confusing SUM with AVG
  • Expecting no grouping effect
  • Thinking SUM causes error with GROUP BY
4. Identify the error in this SQL query:
SELECT department, AVG(salary) FROM employees WHERE department GROUP BY department;
medium
A. Missing condition after WHERE clause.
B. AVG() cannot be used with GROUP BY.
C. GROUP BY should come before WHERE.
D. department cannot be selected with AVG().

Solution

  1. Step 1: Analyze the WHERE clause

    The WHERE clause requires a condition, but here it only has 'department' which is incomplete and invalid.
  2. Step 2: Check GROUP BY and AVG usage

    GROUP BY after WHERE is correct, and AVG() can be used with GROUP BY, so no error there.
  3. Final Answer:

    Missing condition after WHERE clause. -> Option A
  4. Quick Check:

    WHERE needs a condition, not just a column name [OK]
Hint: WHERE must have a condition; column alone is invalid [OK]
Common Mistakes:
  • Using WHERE without condition
  • Thinking GROUP BY order is wrong
  • Believing AVG() can't be grouped
5. You have a products table with columns category, price, and stock. Which query shows the average price and total stock for each category, but only for categories with more than 10 products?
hard
A. SELECT category, AVG(price), SUM(stock) FROM products GROUP BY category HAVING COUNT(*) > 10;
B. SELECT category, AVG(price), SUM(stock) FROM products WHERE COUNT(*) > 10 GROUP BY category;
C. SELECT category, AVG(price), SUM(stock) FROM products GROUP BY category WHERE COUNT(*) > 10;
D. SELECT category, AVG(price), SUM(stock) FROM products HAVING COUNT(*) > 10 GROUP BY category;

Solution

  1. Step 1: Understand filtering groups with HAVING

    To filter groups based on aggregate conditions, use HAVING after GROUP BY.
  2. Step 2: Analyze each option's clause order

    Only SELECT category, AVG(price), SUM(stock) FROM products GROUP BY category HAVING COUNT(*) > 10; correctly uses GROUP BY then HAVING. Using WHERE with COUNT(*) is invalid (WHERE processes rows before grouping), and placing HAVING before GROUP BY or incorrect clause ordering is invalid syntax.
  3. Final Answer:

    SELECT category, AVG(price), SUM(stock) FROM products GROUP BY category HAVING COUNT(*) > 10; -> Option A
  4. Quick Check:

    Use HAVING to filter groups after GROUP BY [OK]
Hint: Use HAVING after GROUP BY to filter groups by aggregate [OK]
Common Mistakes:
  • Using WHERE to filter aggregate results
  • Placing HAVING before GROUP BY
  • Confusing clause order in SQL