Pcornel
Browse topics
Options
Recent
Favorites
Databases · Technical reference

GROUP BY and Aggregates

Direct answer

GROUP BY groups rows and aggregate functions (COUNT, SUM, AVG, MIN, MAX) compute values per group; HAVING filters groups.

When to use this

Use it for reports and summaries.

First 30 seconds

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.

Operational verification

FROM → WHERE → GROUP BY → aggregates → HAVING

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
MariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformMariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
Scope / prerequisiteUse it for reports and summaries.
What next?2 suggested next steps
Evidence0
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

2 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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.

Key points

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.

Key checks
  • SELECT status, count(*) FROM orders GROUP BY status; — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -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_BY enforces it).
  • count(col) ignores NULLs; count(*) counts rows.
  • Window functions (sum() OVER (PARTITION BY ...)) aggregate without collapsing rows.

In depth

NULL handling in aggregates

ExpressionCounts / 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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

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
Terminology layer

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.

Aliases that resolve here
group by and aggregatessql group by havingsql aggregate functions
Confirmation

Confirm action

Continue?