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.
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.
Channel funnel metrics
DoneBuild 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?
- The starter's CTR is 0 because both sums are integers. Use
SUM(d.clicks) * 100.0 / SUM(d.impressions). spendis already a decimal, soSUM(d.spend) / SUM(d.clicks)is safe. Sort withORDER BY cpaor repeat the expression.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
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)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Top campaigns by ROAS
DoneFind 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?
- The starter averages daily ratios. ROAS over a period is total revenue divided by total spend:
SUM(d.revenue) / SUM(d.spend). - Filter campaigns on their total with
HAVING SUM(d.spend) >= 20000, beforeORDER BYandLIMIT.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
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)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)Advertiser ROAS league table
DoneRank 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?
- Put the per-advertiser totals in a CTE, then compute ROAS and the rank from it.
RANK() OVER (ORDER BY revenue / spend DESC)numbers the advertisers from best to worst ROAS.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
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)campaigns (40 rows)daily_stats (1,561 rows)customers (300 rows)orders (900 rows)ab_test (4,000 rows)