SQL Analysis · Chapter 3 of 10

GROUP BY and HAVING

Aggregate PostgreSQL data into trustworthy metrics with grouped calculations and post-aggregate filters.

Why this chapter matters

Team decisions often depend on rollups such as weekly totals, conversion by segment, and top categories.

What you will learn

  • Group rows correctly and compute aggregates like COUNT, SUM, and AVG.
  • Use HAVING to filter aggregated groups after calculation.
  • Avoid mixing non-grouped columns with aggregates incorrectly.

Lessons in this chapter

  1. Aggregation fundamentalsBuild grouped metrics with clear dimension columns and measure columns. Read the full guide →
  2. HAVING versus WHEREApply WHERE before grouping and HAVING after grouping in PostgreSQL query order.
  3. Distinct and conditional countsUse COUNT(DISTINCT ...) and CASE-based aggregates for cleaner KPI definitions.
  4. Metric QA checksValidate grouped totals against known baselines to catch logic mistakes early.

Study task

In PostgreSQL, compute monthly revenue by plan and return only plans whose monthly revenue exceeds 5000.

Chapter checkpoint

When filtering groups with total orders greater than 100, should you use WHERE or HAVING?

Use HAVING because the filter depends on an aggregate computed after GROUP BY.