Using SQL Aggregate Functions

1. Counting Rows

FormCounts
COUNT(*)All rows including NULLs
COUNT(col)Rows where col IS NOT NULL
COUNT(DISTINCT col)Unique non-null values
COUNT(*) FILTER (WHERE ...)Conditional count (PG, standard)

2. Calculating Sums

FunctionNotes
SUM(col)Skips NULLs; returns NULL on empty set
SUM(col) FILTER (WHERE ...)Conditional sum
SUM(CASE WHEN ... THEN x ELSE 0 END)Pre-SQL:2003 conditional sum

3. Finding Averages

FunctionType
AVG(col)Arithmetic mean (NULLs skipped)
PERCENTILE_CONT(0.5)Median (continuous)
PERCENTILE_DISC(0.95)P95 (discrete)
STDDEV, VARIANCESpread
MODE()Most frequent value (PG)

4. Getting Minimum Values

UseExample
MIN(col)SELECT MIN(price) FROM products;
Earliest dateMIN(created_at)
Per groupMIN(col) ... GROUP BY

5. Getting Maximum Values

UseExample
MAX(col)SELECT MAX(score) FROM games;
Latest versionMAX(version) ... GROUP BY
Greatest-N-per-groupUse window functions, not MAX alone

6. Grouping Results

ClauseEffect
GROUP BY colOne row per distinct value
GROUP BY a, bComposite grouping
GROUP BY ROLLUP(a,b)Subtotals + grand total
GROUP BY CUBE(a,b)All combinations
GROUP BY GROUPING SETSCustom group combos

Example: Sales by Region and Month

SELECT region, date_trunc('month', placed_at) AS month,
       SUM(total) AS revenue, COUNT(*) AS orders
FROM orders
GROUP BY region, date_trunc('month', placed_at)
ORDER BY month, region;

7. Filtering Groups

ClauseFilters
WHERERows before grouping
HAVINGGroups after aggregation
QUALIFY (Snowflake, DuckDB)Window function output

Example: HAVING

SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 10;

8. Using Multiple Aggregations

PatternExample
Multiple aggsSUM, AVG, MIN, MAX in same SELECT
Filtered aggsCOUNT(*) FILTER (WHERE status='paid')
PivotMultiple CASE/FILTER aggs to columnize

9. Handling NULL in Aggregations

FunctionNULL Treatment
SUM/AVG/MIN/MAXSkip NULL inputs
COUNT(col)Skip NULL inputs
COUNT(*)Count all rows
Empty setSUM/AVG return NULL; COUNT returns 0
COALESCE(SUM(col), 0)Replace NULL result with 0

10. Creating Rollups and Cubes

FeatureGenerates
ROLLUP(a,b,c)(a,b,c), (a,b), (a), ()
CUBE(a,b)(a,b), (a), (b), ()
GROUPING SETSExplicit list of group combos
GROUPING(col)1 if col is rolled up, else 0