CMD Guide
HomeDatabasesSQL Practice Problems

Ads Performance

Problem

Table Ads(ad_id, user_id, action) where action is an enum of 'Clicked', 'Viewed', or 'Ignored', and (ad_id, user_id) is the primary key. For each ad, compute its click-through rate:

ctr = 0                              if clicks + views = 0
ctr = clicks * 100 / (clicks + views) otherwise

Round to two decimals, and order by ctr DESC, ad_id ASC.

Mechanism

Each SUM(CASE WHEN action = 'X' THEN 1 ELSE 0 END) turns a row-level enum into a per-group counter, so one GROUP BY ad_id pass pivots the action column into as many tallies as you write CASE arms — here, one for clicks and one for clicks+views — and the ratio of those two tallies is the CTR.

SUM(CASE) is a pivot, not a filter

The key idea: a CASE inside an aggregate maps each row to a number, and the aggregate folds those numbers per group. SUM(CASE WHEN cond THEN 1 ELSE 0 END) is therefore a conditional count — it counts rows where cond holds, but unlike WHERE, every row stays in the group. That is what lets you count clicks and count clicks+views in the same scan, side by side, without two subqueries or a self-join. Add another CASE arm and you have another column. This is the bread-and-butter SQL pivot.

diagram
diagram

Solution

SELECT ad_id,
       IFNULL(
         ROUND(
           SUM(CASE WHEN action = 'Clicked' THEN 1 ELSE 0 END)
           / SUM(CASE WHEN action IN ('Clicked','Viewed') THEN 1 ELSE 0 END)
           * 100,
         2),
       0) AS ctr
FROM   Ads
GROUP  BY ad_id
ORDER  BY ctr DESC, ad_id ASC;

The numerator counts clicks; the denominator counts clicks+views; their ratio times 100 is the CTR. ROUND(..., 2) meets the two-decimal requirement. IFNULL(..., 0) handles the all-ignored ad. The ORDER BY sorts by rate descending, breaking ties by ad_id ascending.

Worked trace

Take this input:

ad_id | user_id | action
  1   |   1     | Clicked
  1   |   2     | Clicked
  1   |   3     | Viewed
  2   |   1     | Viewed
  2   |   2     | Viewed
  2   |   3     | Clicked
  3   |   1     | Clicked
  3   |   2     | Viewed
  5   |   1     | Ignored
  5   |   2     | Ignored

Step 1 — conditional counts per group. One scan, two tallies:

ad_idclicks (SUM CASE)total = clicks+views
123
213
312
500

Step 2 — ratio * 100, rounded. Note ad 5's denominator is 0:

ad_idclicks / total * 100ROUND(...,2)IFNULL(...,0)
12/3*100 = 66.666...66.6766.67
21/3*100 = 33.333...33.3333.33
31/2*100 = 50.050.0050.00
50/0 → NULLNULL0.00

Step 3 — order. By ctr DESC, ad_id ASC: 1 (66.67), 3 (50.00), 2 (33.33), 5 (0.00).

ad_id | ctr
  1   | 66.67
  3   | 50.00
  2   | 33.33
  5   |  0.00

The part that's actually engine-specific

For ad 5 the denominator is 0, so the expression is 0 / 0. The whole solution leans on one fact: in MySQL, division by zero yields NULL rather than raising an error. ROUND(NULL, 2) stays NULL, and only then does IFNULL(..., 0) have something to catch — it converts that NULL to 0.00. So IFNULL is not guarding against "the value is 0"; it is guarding against "the division produced NULL."

This is not portable. PostgreSQL raises division by zero and aborts the query — IFNULL never runs, and Postgres doesn't even have IFNULL (use COALESCE). On Postgres you must prevent the division, e.g. with NULLIF(denominator, 0) so the divisor becomes NULL (and the division yields NULL safely), then COALESCE(..., 0):

-- Portable form (Postgres, and works on MySQL too)
SELECT ad_id,
       COALESCE(
         ROUND(
           SUM(CASE WHEN action = 'Clicked' THEN 1 ELSE 0 END) * 100.0
           / NULLIF(SUM(CASE WHEN action IN ('Clicked','Viewed') THEN 1 ELSE 0 END), 0),
         2),
       0) AS ctr
FROM   Ads
GROUP  BY ad_id
ORDER  BY ctr DESC, ad_id ASC;

Here NULLIF(denom, 0) turns a 0 denominator into NULL before the engine attempts the divide, so no engine ever sees a literal x/0. This is the version to reach for in production.

Pitfalls

Takeaways


Problem from LeetCode 1322 "Ads Performance." Division-by-zero semantics per the MySQL Reference Manual (arithmetic operators return NULL on divide-by-zero) and the PostgreSQL manual (raises division_by_zero); NULLIF/COALESCE usage per the SQL standard. Re-authored and deepened for this guide: added the SUM(CASE)-as-pivot mechanism, a three-step worked trace (66.67 / 50.00 / 33.33 / 0.00), the engine-specific divide-by-zero analysis, and a portable Postgres-safe variant.

🤖 Don't fully get this? Learn it with Claude

Stuck on Ads Performance? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Ads Performance** (Databases) and want to truly understand it. Explain Ads Performance from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Ads Performance** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Ads Performance** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Ads Performance** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes