Bird
Raised Fist0
PostgreSQLquery~10 mins

GROUP BY single and multiple columns in PostgreSQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - GROUP BY single and multiple columns
Start with SELECT query
↓
Identify columns to GROUP BY
↓
Scan table rows
↓
Group rows by unique values of GROUP BY columns
↓
Apply aggregate functions on each group
↓
Return grouped result rows
The query scans the table, groups rows by the specified columns, then calculates aggregates for each group and returns the results.
Execution Sample
PostgreSQL
SELECT department, COUNT(*) FROM employees GROUP BY department;

SELECT department, role, AVG(salary) FROM employees GROUP BY department, role;
First query groups employees by department and counts them. Second query groups by department and role, then calculates average salary.
Execution Table
StepActionInput RowsGroup KeyAggregated ResultOutput Rows
1Scan all rows from employees10 rows---
2Group rows by department (single column)10 rowsSalesCount=31 row for Sales
3Group rows by department (single column)10 rowsHRCount=41 row for HR
4Group rows by department (single column)10 rowsITCount=31 row for IT
5Return grouped count results---3 rows total
6Group rows by department and role (multiple columns)10 rows(Sales, Manager)Avg Salary=700001 row for Sales Manager
7Group rows by department and role (multiple columns)10 rows(Sales, Rep)Avg Salary=500001 row for Sales Rep
8Group rows by department and role (multiple columns)10 rows(HR, Recruiter)Avg Salary=600001 row for HR Recruiter
9Group rows by department and role (multiple columns)10 rows(IT, Developer)Avg Salary=800001 row for IT Developer
10Return grouped average salary results---4 rows total
11End of query execution----
💡 All rows processed and grouped by specified columns; aggregates computed and results returned.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 6After Step 7After Step 8After Step 9Final
Group Keys (single column)[][Sales][Sales, HR][Sales, HR, IT][Sales, HR, IT][Sales, HR, IT][Sales, HR, IT][Sales, HR, IT][Sales, HR, IT]
Group Keys (multiple columns)[][][][][(Sales, Manager)][(Sales, Manager), (Sales, Rep)][(Sales, Manager), (Sales, Rep), (HR, Recruiter)][(Sales, Manager), (Sales, Rep), (HR, Recruiter), (IT, Developer)][(Sales, Manager), (Sales, Rep), (HR, Recruiter), (IT, Developer)]
Aggregated Counts{}{"Sales":3}{"Sales":3,"HR":4}{"Sales":3,"HR":4,"IT":3}{}{}{}{}{}
Aggregated Avg Salaries{}{}{}{}
(Sales, Manager): 70000
(Sales, Manager): 70000
(Sales, Rep): 50000
(Sales, Manager): 70000
(Sales, Rep): 50000
(HR, Recruiter): 60000
(Sales, Manager): 70000
(Sales, Rep): 50000
(HR, Recruiter): 60000
(IT, Developer): 80000
(Sales, Manager): 70000
(Sales, Rep): 50000
(HR, Recruiter): 60000
(IT, Developer): 80000
Key Moments - 2 Insights
Why does grouping by multiple columns create more groups than grouping by a single column?
Because grouping by multiple columns considers unique combinations of values from all those columns, not just one. For example, (Sales, Manager) and (Sales, Rep) are different groups even though they share the same department.
What happens if you select a column that is not in GROUP BY or an aggregate function?
The query will cause an error because every selected column must be either grouped or aggregated. This is shown by the grouping keys in the execution_table that must match selected columns.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 4, how many groups exist when grouping by department?
A3 groups
B4 groups
C1 group
D10 groups
💡 Hint
Check the 'Group Key' column at Step 4 showing Sales, HR, IT groups.
At which step does the query start grouping by multiple columns?
AStep 2
BStep 5
CStep 6
DStep 10
💡 Hint
Look for the first step mentioning grouping by department and role in the 'Action' column.
If the employees table had an extra role in Sales, how would the number of groups at Step 9 change?
AIt would decrease by 1
BIt would increase by 1
CIt would stay the same
DIt would double
💡 Hint
Adding a new unique (department, role) combination creates a new group as shown in variable_tracker for multiple columns.
Concept Snapshot
GROUP BY syntax:
SELECT columns, aggregate_function(column) FROM table
GROUP BY column1 [, column2, ...];

Groups rows by unique values of specified columns.
Aggregate functions compute summary per group.
Multiple columns create groups by unique combinations.
Full Transcript
This visual execution shows how SQL GROUP BY works with single and multiple columns. The query scans all rows, then groups them by the specified columns. For single column grouping, rows with the same value in that column form one group. For multiple columns, groups form by unique combinations of those columns' values. Aggregates like COUNT or AVG are calculated per group. The execution table traces each step, showing how groups form and aggregates compute. Variable tracking shows how group keys and aggregates build up. Key moments clarify why multiple columns create more groups and why selected columns must be grouped or aggregated. The quiz tests understanding of group counts and grouping steps. The snapshot summarizes syntax and behavior for quick reference.

Practice

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

Solution

  1. Step 1: Understand the purpose of GROUP BY

    The GROUP BY clause collects rows that share the same value in one or more columns into groups.
  2. Step 2: Differentiate from other clauses

    Unlike ORDER BY which sorts rows, GROUP BY organizes rows into groups for aggregation.
  3. Final Answer:

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

    GROUP BY = groups rows by column values [OK]
Hint: GROUP BY collects rows sharing column values into groups [OK]
Common Mistakes:
  • Confusing GROUP BY with ORDER BY
  • Thinking GROUP BY deletes duplicates
  • Assuming GROUP BY updates data
2. Which of the following is the correct syntax to group data by two columns, category and region?
easy
A. SELECT category, region, COUNT(*) FROM sales GROUP BY category, region;
B. SELECT category, region, COUNT(*) FROM sales GROUP BY category region;
C. SELECT category, region, COUNT(*) FROM sales GROUP BY (category, region);
D. SELECT category, region, COUNT(*) FROM sales GROUP category, region;

Solution

  1. Step 1: Check correct GROUP BY syntax

    In PostgreSQL, multiple columns are separated by commas in GROUP BY without parentheses.
  2. Step 2: Validate each option

    SELECT category, region, COUNT(*) FROM sales GROUP BY category, region; uses commas correctly; SELECT category, region, COUNT(*) FROM sales GROUP BY category region; misses comma; SELECT category, region, COUNT(*) FROM sales GROUP BY (category, region); uses parentheses incorrectly; SELECT category, region, COUNT(*) FROM sales GROUP category, region; misses BY keyword.
  3. Final Answer:

    SELECT category, region, COUNT(*) FROM sales GROUP BY category, region; -> Option A
  4. Quick Check:

    GROUP BY columns separated by commas [OK]
Hint: Separate multiple columns with commas in GROUP BY [OK]
Common Mistakes:
  • Omitting commas between columns
  • Using parentheses around columns
  • Forgetting the BY keyword
3. Given the table orders with columns customer_id, product_id, and quantity, what will this query return?
SELECT customer_id, SUM(quantity) FROM orders GROUP BY customer_id;
medium
A. Total quantity ordered by each customer.
B. Total quantity ordered by each product.
C. Total quantity ordered by each customer and product.
D. Syntax error due to missing GROUP BY columns.

Solution

  1. Step 1: Analyze the SELECT and GROUP BY columns

    The query groups rows by customer_id and sums quantity for each group.
  2. Step 2: Understand the aggregation result

    SUM(quantity) calculates total quantity per customer_id, ignoring product_id.
  3. Final Answer:

    Total quantity ordered by each customer. -> Option A
  4. Quick Check:

    GROUP BY customer_id sums quantity per customer [OK]
Hint: GROUP BY column matches SELECT non-aggregates [OK]
Common Mistakes:
  • Assuming product_id affects grouping
  • Thinking query returns per product totals
  • Confusing aggregation with filtering
4. Identify the error in this query:
SELECT product_id, region, COUNT(*) FROM sales GROUP BY product_id;
medium
A. COUNT(*) cannot be used with GROUP BY.
B. Missing region in GROUP BY causes error.
C. product_id cannot be grouped alone.
D. Syntax error due to missing FROM clause.

Solution

  1. Step 1: Check SELECT columns vs GROUP BY columns

    SELECT includes product_id and region, but GROUP BY only has product_id.
  2. Step 2: Understand PostgreSQL grouping rules

    All non-aggregated columns in SELECT must appear in GROUP BY; region is missing.
  3. Final Answer:

    Missing region in GROUP BY causes error. -> Option B
  4. Quick Check:

    All SELECT non-aggregates must be in GROUP BY [OK]
Hint: Include all non-aggregated SELECT columns in GROUP BY [OK]
Common Mistakes:
  • Forgetting to add all columns to GROUP BY
  • Thinking COUNT(*) disallows grouping
  • Ignoring SELECT and GROUP BY mismatch
5. You want to find the total sales quantity for each product in each region from the sales table with columns product_id, region, and quantity. Which query correctly groups and sums the data?
hard
A. SELECT product_id, SUM(quantity) FROM sales GROUP BY product_id;
B. SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id;
C. SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id, region;
D. SELECT product_id, region, SUM(quantity) FROM sales;

Solution

  1. Step 1: Identify grouping needs

    We want totals per product and per region, so both columns must be grouped.
  2. Step 2: Check each option's GROUP BY clause

    SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id, region; groups by product_id and region, matching SELECT columns; others miss region or GROUP BY entirely.
  3. Final Answer:

    SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id, region; -> Option C
  4. Quick Check:

    Group by all non-aggregated columns for correct totals [OK]
Hint: Group by all selected non-aggregated columns [OK]
Common Mistakes:
  • Grouping by only one column when selecting multiple
  • Omitting GROUP BY causing aggregation errors
  • Selecting columns without aggregation or grouping
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard