Interview Questions/SQL/Campaign Funnel Analysis (View → Cart → Purchase)

Campaign Funnel Analysis (View → Cart → Purchase)

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a table of user events. Each event belongs to a campaign and is one of three types: 'view', 'cart', or 'purchase'. A user may fire multiple events of the same type. Write a SQL query to compute, per campaign: - viewers: distinct users who fired a 'view' event - cart_adds: distinct users who fired a 'cart' event - purchasers: distinct users who fired a 'purchase' event - view_to_cart_pct: ROUND(cart_adds / viewers * 100, 2) - use NULLIF to avoid division by zero - cart_to_purchase_pct: ROUND(purchasers / cart_adds * 100, 2) - use NULLIF to avoid division by zero Return results ordered by campaign. Table: Events

Column NameTypeDescription
idINTPrimary key
user_idINTID of the user
campaignVARCHARCampaign identifier
event_typeVARCHAR'view', 'cart', or 'purchase'
event_dateDATEDate of the event

Database Schema (Inferred)

Events

Column NameExample Value
id1
user_id1
campaignCMP_A
event_typeview
event_date2023-01-01

Example

Events

iduser_idcampaignevent_typeevent_date
11CMP_Aview2023-01-01
21CMP_Acart2023-01-02
31CMP_Apurchase2023-01-03
42CMP_Aview2023-01-01
52CMP_Acart2023-01-04
63CMP_Aview2023-01-05
74CMP_Bview2023-01-01
84CMP_Bpurchase2023-01-03
95CMP_Bview2023-01-01
105CMP_Bcart2023-01-02
115CMP_Bpurchase2023-01-04
126CMP_Bview2023-01-02

Output

campaignviewerscart_addspurchasersview_to_cart_pctcart_to_purchase_pct
CMP_A32166.6750
CMP_B31233.33200

Explanation:

A user who skips 'cart' and goes straight to 'purchase' counts as a purchaser but not a cart_add, which can make cart_to_purchase_pct exceed 100%. Use COUNT(DISTINCT CASE WHEN event_type='x' THEN user_id END) for each stage.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Events

iduser_idcampaignevent_typeevent_date
11CMP_Aview2023-01-01
21CMP_Acart2023-01-02
31CMP_Apurchase2023-01-03
42CMP_Aview2023-01-01
52CMP_Acart2023-01-04
63CMP_Aview2023-01-05
74CMP_Bview2023-01-01
84CMP_Bpurchase2023-01-03
95CMP_Bview2023-01-01
105CMP_Bcart2023-01-02
115CMP_Bpurchase2023-01-04
126CMP_Bview2023-01-02

Output

campaignviewerscart_addspurchasersview_to_cart_pctcart_to_purchase_pct
CMP_A32166.6750
CMP_B31233.33200