Cheat Sheets

SQL Aggregate Functions Cheat Sheet: COUNT, SUM, AVG, GROUP BY & HAVING

By ArpaNeuro Team September 26, 2026
SQL aggregates cheat sheet

Aggregate functions collapse many rows into one value with COUNT, SUM, AVG, MIN, and MAX — the whole result unless you GROUP BY. WHERE filters rows before grouping; HAVING filters groups after. COUNT(*) counts rows, while COUNT(col) ignores NULL in that column.

This SQL cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.

Quick reference

  • COUNT(*): Rows in the group, including NULLs in other columns.
  • COUNT(col): Non-NULL values of col.
  • SUM / AVG: Ignore NULL. AVG of {10, NULL} is 10, not 5.
  • MIN / MAX: Work on numbers, dates, and strings (collation matters).
  • GROUP BY: List the non-aggregated SELECT columns.
  • HAVING: HAVING COUNT(*) >= 2 after grouping.
  • DISTINCT: COUNT(DISTINCT user_id) unique non-null users.
  • Filter first: WHERE reduces rows before the aggregate — cheaper and different from HAVING.

Copy-paste examples

Revenue per day with a minimum count

Date grouping functions are dialect-specific; this form is common in MySQL.

SELECT DATE(paid_at) AS day,
       COUNT(*) AS orders,
       SUM(total) AS revenue,
       AVG(total) AS avg_order
FROM orders
WHERE paid_at IS NOT NULL
GROUP BY DATE(paid_at)
HAVING COUNT(*) >= 3
ORDER BY day DESC;

Common mistakes

  • Using WHERE COUNT(*) > 1 — aggregates belong in HAVING.
  • SUM of a string column and getting 0 or a warning you ignored.
  • Forgetting GROUP BY and selecting extra columns (MySQL loose mode).
  • Counting a left-joined child with COUNT(*) and inflating parent rows — COUNT(child.id) is safer.

FAQ

  1. AVG and empty set? No rows → AVG returns NULL, not 0. Handle that in SQL (COALESCE) or in the app.
  1. Can I GROUP BY an alias? MySQL often allows GROUP BY day if day is in SELECT. Strict SQL wants the expression or a subquery. Do not assume portability.
  1. Window functions vs GROUP BY? SUM() OVER (PARTITION BY …) keeps row detail. GROUP BY collapses. MySQL 8+ supports windows.

Related SQL cheat sheets

Build with this stack

When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.

Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.

← All Articles Get a Quote →