Section 4 · Lesson 3

Marketing metrics in SQL: CTR, CPC, CPA and ROAS

Compute the KPIs every marketing team reports, at any level of detail, without the averaging and division mistakes that skew dashboards.

35 min 3 practice tasks
Basic Media Metrics Explained | CPM | CTR | CPC | CPA | CVR | Programmatic Advertising EP 8 by Bailey Dang on YouTube

Everything in this course comes together here. Ad platforms log raw counts (impressions, clicks, conversions, spend, revenue), but nobody manages a budget by staring at counts. Teams manage by ratios: how often people click, what each click costs, what each customer costs, and how much revenue every dollar of ads returns.

The core metrics

Metric Question it answers Formula SQL (over any group)
CTR Do people click? clicks / impressions SUM(clicks) * 100.0 / SUM(impressions) (as %)
CPM What does reach cost? spend / impressions × 1000 SUM(spend) * 1000 / SUM(impressions)
CPC What does a click cost? spend / clicks SUM(spend) / SUM(clicks)
CVR Do clicks convert? conversions / clicks SUM(conversions) * 100.0 / SUM(clicks) (as %)
CPA What does a customer cost? spend / conversions SUM(spend) / SUM(conversions)
ROAS What comes back per ad dollar? revenue / spend SUM(revenue) / SUM(spend)

A ROAS of 4 means every 1 USD of ads produced 4 USD of revenue. Lower is better for the “cost per” metrics (CPM, CPC, CPA); higher is better for CTR, CVR and ROAS.

They form a chain: impressions → clicks (CTR) → conversions (CVR) → revenue. When CPA rises, the chain tells you where to look: did clicks get pricier (CPC up) or did fewer clicks convert (CVR down)?

Rule 1: sum first, then divide

The most common dashboard error is averaging ratios that were already computed per row. Compare two ways of getting the CTR of display campaigns:

SELECT ROUND(AVG(d.clicks * 100.0 / d.impressions), 2) AS avg_of_daily_ctr,     -- 0.40
       ROUND(SUM(d.clicks) * 100.0 / SUM(d.impressions), 2) AS true_ctr        -- 0.32
FROM daily_stats AS d
JOIN campaigns AS c ON c.id = d.campaign_id
WHERE c.channel = 'display';

The average of daily ratios gives a campaign-day with 90,000 impressions the same weight as one with 1.8 million (both exist in the display data), so small days distort the result. Totals weight every impression equally, which is what CTR means. Always aggregate the numerator and denominator separately at the level you report on (day, campaign, channel, month), then divide. The same SQL pattern works at any level: just change the GROUP BY.

Rule 2: watch the integer division

clicks, impressions and conversions are integers. As you saw in the aggregation section, SUM(clicks) / SUM(impressions) is 0 in SQLite. Multiply by 100.0 (for a percentage) or 1.0 before dividing. spend and revenue are decimals, so CPC, CPA and ROAS are safe.

Rule 3: plan for zero

Some days have spend but zero conversions. Dividing by zero is undefined:

  • SQLite quietly returns NULL for x / 0.
  • PostgreSQL, SQL Server and most warehouses stop the query with an error.

The portable habit is NULLIF, which turns a zero into NULL so the division returns NULL everywhere:

SELECT date, spend, conversions,
       ROUND(spend / NULLIF(conversions, 0), 2) AS cpa
FROM daily_stats
WHERE campaign_id = 102
ORDER BY date;

A NULL CPA honestly says “no conversions, CPA undefined”, which is better than a fake 0 that would make the worst days look like the best ones.

Rule 4: filter out tiny samples

A campaign that spent 50 USD and got one lucky 2,000 USD order has a ROAS of 40, but it proves nothing. When ranking by a ratio, set a minimum volume with HAVING (HAVING SUM(spend) >= 20000 or HAVING SUM(clicks) >= 1000) so the leaderboard reflects real performance.

ROAS isn’t profit

ROAS ignores product costs, refunds and overhead. A ROAS of 2 can still lose money if margins are thin. In our data, revenue is attributed revenue reported by the ad platform; the orders table is a separate system, which is why the two don’t reconcile exactly. That’s normal in marketing analytics, and knowing which source a number comes from is part of the job.

About the video: it explains these metrics from a media buyer’s point of view. It reads CPA as “cost per action”; in our data the action is a conversion, so it’s the same formula. ROAS isn’t among the metrics it covers, so use the table above for that one.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Channel funnel metrics

Build a funnel report per channel with five columns, in this order: 1. channel 2. CTR as a percentage: clicks / impressions × 100 3. CPC: spend / clicks 4. conversion rate as a percentage: conversions / clicks × 100 5. CPA: spend / conversions

Compute every metric from the channel's totals (sum first, then divide) and round each to 2 decimals. Sort by CPA, cheapest first.

Need a hint?
  1. The starter's CTR is 0 because both sums are integers. Use SUM(d.clicks) * 100.0 / SUM(d.impressions).
  2. spend is already a decimal, so SUM(d.spend) / SUM(d.clicks) is safe. Sort with ORDER BY cpa or repeat the expression.
SQL · SQLite
SELECT c.channel,
       SUM(d.clicks) / SUM(d.impressions) * 100 AS ctr_pct
FROM daily_stats AS d
JOIN campaigns AS c ON c.id = d.campaign_id
GROUP BY c.channel;
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
2

Top campaigns by ROAS

Find the 5 campaigns with the highest ROAS (total revenue / total spend), considering only campaigns with total spend of at least 20,000 USD so that tiny tests don't top the list. Return the campaign name, total spend, total revenue and ROAS, each number rounded to 2 decimals. Sort by ROAS, highest first.

Need a hint?
  1. The starter averages daily ratios. ROAS over a period is total revenue divided by total spend: SUM(d.revenue) / SUM(d.spend).
  2. Filter campaigns on their total with HAVING SUM(d.spend) >= 20000, before ORDER BY and LIMIT.
SQL · SQLite
SELECT c.name,
       ROUND(SUM(d.spend), 2) AS spend,
       ROUND(SUM(d.revenue), 2) AS revenue,
       ROUND(AVG(d.revenue / d.spend), 2) AS roas
FROM daily_stats AS d
JOIN campaigns AS c ON c.id = d.campaign_id
GROUP BY c.id, c.name
ORDER BY roas DESC
LIMIT 5;
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue
3

Advertiser ROAS league table

Rank all advertisers by ROAS. Return five columns: advertiser name, total spend, total revenue, ROAS (revenue / spend) and the advertiser's rank by ROAS using RANK() (1 = highest ROAS). Round spend, revenue and ROAS to 2 decimals. Sort by rank.

Need a hint?
  1. Put the per-advertiser totals in a CTE, then compute ROAS and the rank from it.
  2. RANK() OVER (ORDER BY revenue / spend DESC) numbers the advertisers from best to worst ROAS.
SQL · SQLite
SELECT a.name,
       ROUND(SUM(d.spend), 2) AS spend,
       ROUND(SUM(d.revenue), 2) AS revenue
FROM daily_stats AS d
JOIN campaigns AS c ON c.id = d.campaign_id
JOIN advertisers AS a ON a.id = c.advertiser_id
GROUP BY a.id, a.name;
Tables in this database
advertisers (12 rows)
id, name, industry, country
campaigns (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders (900 rows)
id, customer_id, campaign_id, order_date, amount, status
ab_test (4,000 rows)
user_id, variant, device, time_on_page_sec, converted, revenue