Top Ad Campaigns by Revenue

An easy SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
easy
Seniority
L3
Asked in
Audible

Problem

The revenue leaderboard only has room for five campaigns. Across every impression in ad_impressions, give the ad ops team the five campaigns with the highest total ad revenue, biggest first.

Every campaign has a bottom line. Stack them up.

Tables

ad_impressions

Columns: impression_id INTEGER, user_id INTEGER, ad_campaign TEXT, impression_time TEXT, clicked INTEGER, revenue REAL

ad_impressions: 10 of 200 rows
impression_iduser_idad_campaignimpression_timeclickedrevenue
253100BRAND_AWARENESS_Q12026-02-02 01:07:000NULL
306197PRODUCT_LAUNCH_X2026-03-03 02:14:000NULL
359294RETARGETING_CART2026-04-04 03:21:000NULL
412391HOLIDAY_PROMO2026-05-05 04:28:000NULL
465488NEW_USER_ACQU2026-06-06 05:35:0010.2
518NULLLOYALTY_PROGRAM2026-07-07 06:42:000NULL
571682FLASH_SALE_48H2026-08-08 07:49:000NULL
624779SUMMER_SALE_20242026-09-09 08:56:000NULL
677876BRAND_AWARENESS_Q12026-01-10 09:03:000NULL
730973PRODUCT_LAUNCH_X2026-02-11 10:10:0010.35

Expected output

First 5 of 5 rows
ad_campaigntotal_revenue
LOYALTY_PROGRAM215.35
SUMMER_SALE_202416.7
HOLIDAY_PROMO6.2
FLASH_SALE_48H5.6
PRODUCT_LAUNCH_X5

Worked solution and explanation

What this really is

Strip off the leaderboard costume and this is a grouped total finished with a top-N cut. Summing revenue per campaign is the half everyone writes. What actually gets graded is whether you finish the job: sort the campaigns by that total and keep only the five the board has room for. Leave the cut off and you hand back all eight campaigns in ad_impressions, three of which never belonged on the board. Sort raw impression rows before totaling and every number you return is one impression's revenue, not a campaign's.


Break down the requirements

Step 1: Total revenue per campaign

GROUP BY ad_campaign with SUM(revenue) collapses the many impression rows per campaign into one total. Unclicked impressions carry a NULL revenue, and SUM skips them on its own, so they neither zero out a campaign nor drop it.

Step 2: Sort, then keep the leaders

ORDER BY total_revenue DESC puts the biggest earners on top, then LIMIT 5 keeps the leaders. The order is what gives the cut its meaning: without it, LIMIT 5 returns five arbitrary campaigns.


The solution

Sum revenue per campaign, sort descending, keep the top five
SELECT
    ad_campaign,
    SUM(revenue) AS total_revenue
FROM ad_impressions
GROUP BY ad_campaign
ORDER BY total_revenue DESC
LIMIT 5

Common follow-up questions