The snippet library.
Small, practical examples. Search by task or narrow things down below.
Calculate each group’s integer percentage of the total
SQL: Multiply before division and protect against a zero denominator.
SQL✓ Tested
Calculate each group’s numeric spread
SQL: Subtract MIN from MAX to report the difference between extremes.
SQL✓ Tested
Compute an integer weighted average
SQL: Multiply before summing and guard a zero total weight with NULLIF.
SQL✓ Tested
Count distinct values within a result
SQL: COUNT DISTINCT counts distinct non-null values.
SQL✓ Tested
Count rows satisfying separate conditions
SQL: SUM over CASE expressions calculates several conditional counts in one scan.
SQL✓ Tested
Distinguish row count from non-null value count
SQL: COUNT(*) includes every row while COUNT(column) skips NULL values.
SQL✓ Tested
Filter rows before grouping
SQL: WHERE limits the rows contributing to the aggregate; it differs from filtering completed groups with HAVING.
SQL✓ Tested
Group by more than one field
SQL: Each distinct combination of grouping fields produces its own row.
SQL✓ Tested
Return zero for a sum over no rows
SQL: SUM produces NULL for an empty input; COALESCE supplies the desired reporting default.
SQL✓ Tested
Turn known group values into columns
SQL: Conditional aggregation gives a portable pivot when the category set is known.
SQL✓ Tested