Use it for reports and summaries.
GROUP BY and Aggregates
GROUP BY groups rows and aggregate functions (COUNT, SUM, AVG, MIN, MAX) compute values per group; HAVING filters groups.
1. Expected groups and totals: SELECT status, count(*) FROM orders GROUP BY status;.
2. Non-aggregated columns in GROUP BY.
3. WHERE vs HAVING.
4. NULL handling in counts.
5. Cross-check totals.
FROM → WHERE → GROUP BY → aggregates → HAVING
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 How to verify Verify boundary
Cross-check one group by hand. Look at EXPLAIN for large sorts or hash aggregates that spill to disk.
Step 2 Common failures Narrow the fault
MySQL without ONLY_FULL_GROUP_BY returns arbitrary values for ungrouped columns. avg() ignores NULLs, which may not be what the report means. Grouping by a timestamp without truncation makes one group per row.
Every non-aggregated selected column must be in GROUP BY (strict modes). Filter rows with WHERE before grouping; filter groups with HAVING. COUNT(col) skips NULLs; COUNT(*) does not.
SELECT status, count(*) FROM orders GROUP BY status;— first check for this topicpsql -c "SELECT now(), version();"— PostgreSQL reachable and versionmysql -e "SELECT NOW(), VERSION();"— MariaDB/MySQL reachable and versionsqlcmd -S <server> -Q "SELECT @@VERSION"— SQL Server reachable and version
ReferenceWhat it is1 section · depth on demand
How it works
The database sorts or hashes rows into groups and computes one result per group. Joins that multiply rows before grouping inflate sums and counts. Window functions compute aggregates without collapsing rows.
ReferenceImportant terms & boundaries3 sections · depth on demand
Examples
SELECT country, count(*) AS customers, avg(lifetime_value) AS avg_value
FROM customers
GROUP BY country
HAVING count(*) > 100
ORDER BY customers DESC;
- WHERE filters rows before grouping; HAVING filters groups.
- Every selected column must be grouped or aggregated (MySQL's
ONLY_FULL_GROUP_BYenforces it). count(col)ignores NULLs;count(*)counts rows.- Window functions (
sum() OVER (PARTITION BY ...)) aggregate without collapsing rows.
In depth
NULL handling in aggregates
| Expression | Counts / uses |
|---|---|
count(*) | Every row |
count(col) | Rows where col is not NULL |
count(DISTINCT col) | Distinct non-NULL values |
sum(col), avg(col) | Ignore NULLs; sum of only NULLs is NULL, not 0 — use coalesce(sum(col), 0) |
avg(coalesce(col, 0)) | Treats missing as zero — a different question |
Conditional aggregation — one pass instead of several queries
SELECT date_trunc('day', created_at) AS day,
count(*) AS orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded, -- PostgreSQL
sum(CASE WHEN channel = 'web' THEN total ELSE 0 END) AS web_revenue -- portable
FROM orders
WHERE created_at >= now() - interval '30 days'
GROUP BY 1 ORDER BY 1;
WHERE vs HAVING
WHERE removes rows before grouping (can use indexes); HAVING removes groups after aggregation. Put plain row conditions in WHERE — HAVING country = 'DK' works but groups every country first.
Window functions keep the rows
SELECT customer_id, id, total,
sum(total) OVER (PARTITION BY customer_id ORDER BY created_at) AS running_total,
row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders;
-- latest order per customer: wrap it and filter rn = 1
Grouping by time correctly
date_trunc('day', created_at) groups by the session time zone's day for timestamptz; set the zone explicitly (created_at AT TIME ZONE 'Europe/Copenhagen') for reports, otherwise "per day" totals shift by one or two hours of orders.
Common mistakes
- Non-aggregated columns in SELECT with GROUP BY.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Terms & aliases
Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.