GROUP BY single and multiple columns in PostgreSQL - Time & Space Complexity
When using GROUP BY in SQL, the database groups rows based on column values.
We want to understand how the time to group data changes as the data grows.
Analyze the time complexity of these two queries:
-- Group by a single column
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
-- Group by multiple columns
SELECT department, role, COUNT(*)
FROM employees
GROUP BY department, role;
These queries count employees grouped by one or two columns.
Look for repeated work done by the database:
- Primary operation: Scanning all rows in the employees table once.
- How many times: Once for each query, but grouping work depends on number of rows.
The database reads each row and places it into a group based on column values.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 grouping steps |
| 100 | About 100 grouping steps |
| 1000 | About 1000 grouping steps |
Pattern observation: The work grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to group grows linearly as the number of rows increases.
[X] Wrong: "Grouping by more columns always makes the query much slower in a way that grows faster than the number of rows."
[OK] Correct: Grouping time mainly depends on scanning rows once; adding more columns changes grouping keys but does not multiply the number of rows processed.
Understanding how grouping scales helps you explain query performance clearly and shows you know how databases handle data.
What if we added an ORDER BY after GROUP BY? How would that affect the time complexity?
Practice
GROUP BY clause do in a PostgreSQL query?Solution
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.Step 2: Differentiate from other clauses
Unlike ORDER BY which sorts rows, GROUP BY organizes rows into groups for aggregation.Final Answer:
It groups rows that have the same values in specified columns. -> Option DQuick Check:
GROUP BY = groups rows by column values [OK]
- Confusing GROUP BY with ORDER BY
- Thinking GROUP BY deletes duplicates
- Assuming GROUP BY updates data
category and region?Solution
Step 1: Check correct GROUP BY syntax
In PostgreSQL, multiple columns are separated by commas in GROUP BY without parentheses.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.Final Answer:
SELECT category, region, COUNT(*) FROM sales GROUP BY category, region; -> Option AQuick Check:
GROUP BY columns separated by commas [OK]
- Omitting commas between columns
- Using parentheses around columns
- Forgetting the BY keyword
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;
Solution
Step 1: Analyze the SELECT and GROUP BY columns
The query groups rows by customer_id and sums quantity for each group.Step 2: Understand the aggregation result
SUM(quantity) calculates total quantity per customer_id, ignoring product_id.Final Answer:
Total quantity ordered by each customer. -> Option AQuick Check:
GROUP BY customer_id sums quantity per customer [OK]
- Assuming product_id affects grouping
- Thinking query returns per product totals
- Confusing aggregation with filtering
SELECT product_id, region, COUNT(*) FROM sales GROUP BY product_id;
Solution
Step 1: Check SELECT columns vs GROUP BY columns
SELECT includes product_id and region, but GROUP BY only has product_id.Step 2: Understand PostgreSQL grouping rules
All non-aggregated columns in SELECT must appear in GROUP BY; region is missing.Final Answer:
Missing region in GROUP BY causes error. -> Option BQuick Check:
All SELECT non-aggregates must be in GROUP BY [OK]
- Forgetting to add all columns to GROUP BY
- Thinking COUNT(*) disallows grouping
- Ignoring SELECT and GROUP BY mismatch
sales table with columns product_id, region, and quantity. Which query correctly groups and sums the data?Solution
Step 1: Identify grouping needs
We want totals per product and per region, so both columns must be grouped.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.Final Answer:
SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id, region; -> Option CQuick Check:
Group by all non-aggregated columns for correct totals [OK]
- Grouping by only one column when selecting multiple
- Omitting GROUP BY causing aggregation errors
- Selecting columns without aggregation or grouping
Ready to prove it?
Pass the test and this pattern moves unknown
