sql patterns
SQL week over week alert: windows and thresholds
A SQL week over week alert that stays quiet on normal dips: which windows to compare, and how to set thresholds when counts are small.
SELECT
coalesce(sum(amount) FILTER (WHERE created_at >= current_date - 7), 0) AS this_week,
coalesce(sum(amount) FILTER (WHERE created_at < current_date - 7), 0) AS last_week,
round(100.0 * (
coalesce(sum(amount) FILTER (WHERE created_at >= current_date - 7), 0)
- coalesce(sum(amount) FILTER (WHERE created_at < current_date - 7), 0))
/ nullif(sum(amount) FILTER (WHERE created_at < current_date - 7), 0), 1) AS pct_change
FROM orders
WHERE created_at >= current_date - 14 AND created_at < current_date;