SQL Business Metrics

A trustworthy business metric makes its grain, numerator, denominator, and zero handling explicit.

What & Why

Business metrics often compare two aggregates from the same population. The aggregates do not have to be row counts: campaign email rates divide SUM(opens) or SUM(clicks) by SUM(recipients) within each campaign.

The calculation is only meaningful when the result grain and denominator are documented, and NULLIF protects groups whose denominator is zero.

See How It Works

BUSINESS QUESTION

Calculate campaign email open and click rates from total sends.

idcampaign_idsent_atrecipientsopensclicksunsubscribesbounces
20112024-01-20 15:00:00+001200540180924
20222024-02-15 16:30:00+0080042096512
20332024-03-18 13:00:00+0015006102251431
20442024-04-08 14:00:00+0000000
EXAMPLE QUERY
SELECT
  campaign_id,
  SUM(recipients) AS recipients,
  SUM(opens) AS opens,
  SUM(clicks) AS clicks,
  ROUND(SUM(opens)::numeric / NULLIF(SUM(recipients), 0) * 100, 2) AS open_rate_pct,
  ROUND(SUM(clicks)::numeric / NULLIF(SUM(recipients), 0) * 100, 2) AS click_rate_pct
FROM marketing.email_sends
GROUP BY campaign_id
ORDER BY click_rate_pct DESC NULLS LAST, campaign_id;
RESULT — email metrics by campaign
campaign_idrecipientsopensclicksopen_rate_pctclick_rate_pct
1120054018045.0015.00
3150061022540.6715.00
28004209652.5012.00
4000NULLNULL

The rates use recipients from the same campaign group as their numerator.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario