MediumJoins
Ad Campaign Attribution & ROI
Frequently Asked By:AmazonGoogleMeta
Interactive In-Browser Workspace
Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.
Problem Statement
Join `ad_campaigns` with `deals` to compute campaign revenue efficiency.
Calculate:
1. `campaign_name`
2. `channel`
3. `budget_spent`
4. `revenue_generated`: Sum of `deal_value` for `'closed_won'` deals (coalesced to `0` if none)
5. `roas`: Return on Ad Spend, calculated as `ROUND(SUM(d.deal_value) / c.budget_spent, 2)`
Only include campaigns where at least one closed-won deal exists.
Order the output by `roas` in **descending** order.
Why Technical Interviewers Ask This
The performance marketing director needs an attribution report connecting advertising spend to confirmed closed-won revenue from the CRM deals table.
Common Pitfalls & Interview Traps
Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass joins constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
c.campaign_name,
c.channel,
c.budget_spent,
SUM(d.deal_value) AS revenue_generated,
ROUND(SUM(d.deal_value) / c.budget_spent, 2) AS roas
FROM ad_campaigns c
JOIN deals d ON c.campaign_id = d.campaign_id
WHERE d.deal_status = 'closed_won'
GROUP BY c.campaign_id, c.campaign_name, c.channel, c.budget_spent
ORDER BY roas DESC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Joins. It meets the target criteria: Campaign performance metrics with campaign_name, channel, budget_spent, revenue_generated, and roas.Edge Cases to Verbally Clarify with Your Interviewer
The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.
Frequently Asked Follow-Up Questions
What makes this question a favorite among Amazon and Google interviewers?
Interviewers use this problem to test whether candidates write defensive, scalable Joins queries that run efficiently on multi-million row production databases without excessive memory usage.
How does the query optimizer execute this query?
Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.