Explain it simply
GROUP BY in plain language
GROUP BY sorts rows into piles by the value of the columns you name, then folds each pile into one result row. That row can hold only the value that labels the pile, such as the department name, and aggregates computed from the rows in the pile, such as a count or an average.
Picture staff cards spread on a desk and sorted into piles by department. Counting each pile and averaging its salaries is GROUP BY with aggregates. WHERE removes cards before sorting, for example people who have left, and HAVING removes whole piles afterwards, for example piles with fewer than two cards.
Problem → Why → Solution
The problem: an aggregate inside WHERE
HR wants the average salary of every department that has at least two active employees. The first instinct is to put both conditions in WHERE, and PostgreSQL rejects it at once. A second attempt also adds full_name to the SELECT to show the people, and that produces a different error.
SELECT department, AVG(salary)
FROM employees
WHERE active = TRUE AND COUNT(*) >= 2
GROUP BY department;
-- ERROR: aggregate functions are not allowed in WHERE
SELECT department, full_name, COUNT(*)
FROM employees
GROUP BY department;
-- ERROR: column "employees.full_name" must appear in the GROUP BY clause
-- or be used in an aggregate functionWhy this happens
WHERE tests each row before any group exists, so at that point there is no group for COUNT(*) to count. The second error appears because a department contains many names and PostgreSQL cannot know which one to put in the single result row. Filtering groups is HAVING's job, and every selected column must either define the group or be an aggregate.
Core concept: from rows to groups
You write SELECT first, but PostgreSQL works through the clauses in the logical order below. Notice that each clause sees only the rows or groups produced by the clause before it.
| Step | Clause | What it works on |
|---|---|---|
| 1 | FROM / JOIN | all rows of the tables |
| 2 | WHERE | keeps or drops individual rows |
| 3 | GROUP BY | folds the remaining rows into groups |
| 4 | HAVING | keeps or drops whole groups |
| 5 | SELECT | computes output columns and aliases |
| 6 | ORDER BY | sorts the result; aliases work here |
This order explains most of the rules. Aggregates are not allowed in WHERE, because no groups exist yet. SELECT runs after HAVING, so PostgreSQL does not let HAVING refer to a SELECT alias such as employee_count; you repeat COUNT(*) instead, although MySQL does allow the alias. ORDER BY runs last, so aliases work there. Dropping rows early with WHERE also makes the query faster, because fewer rows have to be grouped.
Every column in SELECT must either appear in GROUP BY or sit inside an aggregate. PostgreSQL has one exception: when you group by a table's primary key, you may select that table's other columns, because one key value identifies one row. NULL values are collected into a single group, so employees without a department show up as one row whose department is NULL.
Aggregate functions have their own rules for NULL. COUNT(*) counts every row, while COUNT(salary) counts only rows where salary is not NULL. SUM, AVG, MIN and MAX skip NULLs and work with the remaining values, so AVG is the average of the known values and never treats NULL as zero. When a group has no values at all, SUM returns NULL, not 0.
- WHERE gates single rows
- GROUP BY piles equal values
- Aggregates summarise each pile
- HAVING gates whole piles
If one row is enough to decide a condition, put it in WHERE; if you must see the whole group, put it in HAVING.
General pattern
SELECT group_column,
AGGREGATE(expression) AS alias
FROM table_name
WHERE row_condition
GROUP BY group_column
HAVING AGGREGATE(expression) comparison value
ORDER BY alias DESC;AGGREGATE stands for a function such as COUNT, SUM, AVG, MIN or MAX. WHERE and HAVING are both optional, but when present they must appear in this order.
Worked example: a salary report per department
The employees table holds nine people: five in Engineering (one inactive), two in Support and two in Sales (one inactive). The query keeps only active employees, groups them by department and shows only departments with at least two active people. Try to predict why Sales is missing.
SELECT department,
COUNT(*) AS employee_count,
ROUND(AVG(salary), 2) AS average_salary
FROM employees
WHERE active = TRUE
GROUP BY department
HAVING COUNT(*) >= 2
ORDER BY average_salary DESC;Code breakdown
- Row filter
WHERE active = TRUERemoves the two inactive employees, Hla Hla and Kyaw Kyaw, before grouping, so Engineering's 3000000 salary never enters the average.
- Make the groups
GROUP BY departmentFolds the seven remaining rows into three groups: Engineering (4), Support (2) and Sales (1).
- Aggregates per group
ROUND(AVG(salary), 2) AS average_salaryAVG returns a numeric average of the integer salaries and ROUND(..., 2) fixes two decimal places: Engineering is (1500000 + 1700000 + 2000000 + 2200000) / 4 = 1850000.00.
- Group filter
HAVING COUNT(*) >= 2Drops the Sales group, which has only one active employee. PostgreSQL does not accept the employee_count alias here, so COUNT(*) is written again.
- Sort by an alias
ORDER BY average_salary DESC;ORDER BY runs after SELECT, so the alias is available here.
department | employee_count | average_salary
------------+----------------+---------------
Engineering | 4 | 1850000.00
Support | 2 | 950000.00How the rows flow
Rows to groups in the worked example
------------------------------------
employees (9 rows)
|
v WHERE active = TRUE -> drops Hla Hla, Kyaw Kyaw
7 rows
|
v GROUP BY department
Engineering (4) Support (2) Sales (1)
|
v HAVING COUNT(*) >= 2 -> drops Sales
Engineering (4) Support (2)
|
v SELECT ... ORDER BY average_salary DESC
2 result rowsWhen you want to count several conditions inside each group at once, PostgreSQL's FILTER clause helps. The query below produces, per department, the total headcount, the number of active people and the salary total in one pass. There is no WHERE, so inactive people count towards the headcount: Engineering (5, 4, 10400000), Sales (2, 1, 2300000) and Support (2, 2, 1900000). Databases without FILTER can use COUNT(CASE WHEN active THEN 1 END).
SELECT department,
COUNT(*) AS headcount,
COUNT(*) FILTER (WHERE active) AS active_count,
SUM(salary) AS payroll
FROM employees
GROUP BY department
ORDER BY department;In real projects
GROUP BY in real projects
Almost every number on a dashboard is some GROUP BY query: signups per day, sales per product category, API errors per status code. Time series usually group by an expression such as date_trunc('day', created_at), and HAVING turns up in alert conditions such as endpoints with more than 100 errors today.
- Data-quality checks find duplicate records with SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1, so they can be cleaned up before a UNIQUE constraint is added.
- Finance reports produce monthly revenue with GROUP BY date_trunc('month', paid_at), summing numeric amounts rather than floats so no rounding errors creep in.
- On tables with millions of rows, a WHERE on an indexed column cuts the rows before grouping; HAVING cannot reduce the work that way.
Common mistakes
Common GROUP BY mistakes
Selecting a non-aggregated column that is not grouped
SELECT department, full_name, COUNT(*) ... GROUP BY department errors in PostgreSQL. Older MySQL setups with ONLY_FULL_GROUP_BY disabled silently return an arbitrary name instead, which is worse. Add the column to GROUP BY or wrap it in an aggregate such as MIN(full_name) or string_agg(full_name, ', ').
Putting a row condition in HAVING
HAVING department <> 'Sales' works in PostgreSQL, but it groups every row first and discards the group later, which is extra work and harder to read. Move conditions that a single row can decide into WHERE.
Using a SELECT alias in HAVING
HAVING employee_count >= 2 fails in PostgreSQL with column "employee_count" does not exist, which often bites when a query that worked in MySQL is ported. Repeat the aggregate expression inside HAVING.
Best practices
Best practices
- Before writing the query, decide what one result row represents (a department, a customer, a day); that is your GROUP BY column.
- Give every aggregate a clear name with AS; app code and report tools read it far better than the default name count.
- Always add ORDER BY, because GROUP BY does not guarantee any order of the result.
Mini challenge
Mini challenge: big-spending customers
From the orders table (order_id, customer, amount), calculate each customer's total spend and order count, and show only the customers whose total exceeds 100000.
- GROUP BY customer
- Name SUM(amount) total_amount and COUNT(*) order_count
- Keep only totals above 100000 with HAVING (exactly 100000 does not qualify)
- Sort by total_amount, highest first, with ties broken by customer name
SELECT customer
-- TODO: total spend as total_amount
-- TODO: number of orders as order_count
FROM orders
-- TODO: one row per customer
-- TODO: keep only customers whose total is above 100000
-- TODO: biggest total first, ties by customer
;Expected: Two rows: Chan (120000.00, 1 order) and Aye (115000.00, 2 orders). Bo (95000.00) and Dee (100000.00) are left out.
Show hint
PostgreSQL does not know the total_amount alias inside HAVING, so write SUM(amount) > 100000. Dee's total of exactly 100000 fails >, a boundary case included on purpose.
Show solution
SELECT customer,
SUM(amount) AS total_amount,
COUNT(*) AS order_count
FROM orders
GROUP BY customer
HAVING SUM(amount) > 100000
ORDER BY total_amount DESC, customer;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- GROUP BY collects rows with equal values into groups, and aggregates fold each group into one row.
- Logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY; WHERE tests rows, HAVING tests groups.
- Every selected column must be grouped or aggregated, except other columns of a table grouped by its primary key.
- In PostgreSQL, HAVING cannot see SELECT aliases, so repeat the aggregate; FILTER counts several conditions at once.
Aggregate Functions Tutorial — PostgreSQL
Aggregate Functions Tutorial — PostgreSQL