Skip to main content

GROUP BY

GROUP BY turns detail rows into summary rows. You use it for reporting, dashboards, and data quality checks.

Concept Flow

flowchart LR
A[Raw rows] --> B[Filter with WHERE]
B --> C[Group rows]
C --> D[Aggregate values]
D --> E[Sort and present]

Syntax Patterns

PatternWhen to useExample
Single key groupingOne summary per categoryGROUP BY department_id
Multi-key groupingHierarchical summariesGROUP BY country, city
Group + aggregateCompute metrics per groupCOUNT(*), SUM(amount)
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id;

Practical Example

Sales by Region

SELECT region,
COUNT(*) AS orders,
SUM(total_amount) AS revenue,
AVG(total_amount) AS avg_order
FROM orders
WHERE order_date >= '2026-01-01'
GROUP BY region
ORDER BY revenue DESC;
regionordersrevenueavg_order
APAC210129450.00616.43
EU175102300.00584.57
US320189100.00590.94

Common Pitfalls

PitfallConsequencePrevention
Selecting non-grouped, non-aggregated columnsQuery fails in strict SQL mode or returns ambiguous dataSelect only grouped columns or aggregate functions
Grouping too many columnsFragmented result with tiny groupsStart with reporting key, then add columns intentionally
Missing pre-filter with WHERESlower scans and noisy metricsRestrict input rows before grouping

Quick Reference

SELECT key_col, COUNT(*) FROM t GROUP BY key_col;
SELECT key_col, SUM(amount) FROM t WHERE status = 'paid' GROUP BY key_col;
SELECT key_a, key_b, AVG(score) FROM t GROUP BY key_a, key_b;

What's Next