# Top Ad Campaigns by Revenue

> Every campaign has a bottom line. Stack them up.

Canonical URL: <https://datadriven.io/problems/top_ad_campaigns_by_revenue>

Domain: SQL · Difficulty: easy · Seniority: L3

## Problem

The ad ops team is preparing the quarterly revenue report and needs each campaign's total ad revenue, from the highest-earning campaign down.

## Worked solution and explanation

### Why this problem exists in real interviews

The `ad_impressions` table is the foundation for this filtering to the top rows after aggregation problem. It tests whether you can compose a CTE or subquery that aggregates before ranking, then filter to the desired slice.

---

### Break down the requirements

#### Step 1: Aggregate per ad_campaign

`GROUP BY ad_campaign` with the appropriate aggregate function produces one summary row per group from the `ad_impressions` table.

#### Step 2: Rank the results

`ORDER BY` the aggregate descending with `LIMIT` to surface the top entries.

---

### The solution

**Sum revenue per ad_campaign from ad_impressions and sort descending**

```sql
SELECT
    ad_campaign,
    SUM(revenue) AS total_revenue
FROM ad_impressions
GROUP BY ad_campaign
ORDER BY total_revenue DESC
LIMIT 10
```

> **Cost Analysis**
>
> The GROUP BY reduces the 200M-row `ad_impressions` table to the number of distinct `ad_campaign` values. A covering index on `(ad_campaign, revenue)` enables an index-only aggregate scan.

> **Interviewers Watch For**
>
> Interviewers verify you aggregate before sorting. Sorting raw rows gives per-row values, not group totals. The correct grain is one row per `ad_campaign`.

> **Common Pitfall**
>
> Using the wrong aggregate function. `SUM` gives totals, `COUNT` gives volume, `AVG` gives rates. Read the prompt to determine which metric is needed.

---

## Common follow-up questions

- If some impressions have NULL revenue (organic placements), how does SUM treat those rows? _(Tests knowledge that SUM skips NULLs, which may undercount if NULLs should map to zero.)_
- Would you include campaigns with zero total revenue in the output? _(Tests whether filtering with HAVING > 0 is appropriate or if zero-revenue campaigns are meaningful.)_
- How would you add a column showing each campaign's percentage of total revenue? _(Tests ability to use a window SUM or scalar subquery for the denominator alongside the grouped query.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/top_ad_campaigns_by_revenue)
- [SQL Interview Questions](https://datadriven.io/sql-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.