Avoid Fan-Out When Joining Campaign Budgets to Daily Spend
Last updated: November 29, 2026
Quick Overview
You have an ad campaign budget table with one row per campaign per budget change and a daily spend table. Report, per campaign, total lifetime spend and the current budget, without inflating spend through the join.
Meta
November 29, 20260
0
0 solved
You have an ad campaign budget table with one row per campaign per budget change and a daily spend table. Report, per campaign, total lifetime spend and the current budget, without inflating spend through the join.
Meta ads analytics questions often hide a one-to-many join that multiplies sums. The interviewer is looking for whether you notice the grain mismatch and aggregate or dedupe before joining.
What the Interviewer Expects
- Identifies the grain of each table before joining
- Explains why joining spend to all budget rows multiplies spend
- Reduces the budget table to one current row per campaign first
- Aggregates spend separately, then joins the two one-row-per-campaign results
- Keeps campaigns with spend but no budget row via LEFT JOIN or full outer join
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you report spend against the budget that was active on each day instead?
- How would you detect fan-out in someone else's query?
- What if a campaign has no spend yet?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
campaign_budget(campaign_id, daily_budget, effective_at) has many rows per campaign because advertisers change budgets. daily_spend(campaign_id, spend_date, spend_usd) has one row per campaign per...
Approach
Bring both sides to one row per campaign, then join:
- Current budget: ROW_NUMBER over
effective_at DESC, keep 1. - Lifetime spend: SUM grouped by campaign.
- Full outer join so campaigns with on...