runtime
20 / 88

lesson 20 Joins & sets · intermediate

Ratios, ROUND & NULLIF

Calculate safe ratios and round your results.

the idea

A rate is numerator divided by denominator. Use a real number (100.0) to avoid integer division. NULLIF(x,0) turns a zero denominator into NULL; ROUND controls displayed precision. Preserve that NULL instead of calling an undefined rate zero.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

ai_requests7 columns · 12 rows
idinteger · keyaccount_idintegermodeltextrequested_attextinput_tokensintegeroutput_tokensintegerstatustext
11swift2025-01-01 10:00:001000200success
21reason2025-01-02 11:00:002000600success
32swift2025-01-02 12:00:005000error
43reason2025-01-02 13:00:0080002000success
53swift2025-01-03 14:00:0040001000success

showing 5 of 12 rows

ai_accounts4 columns · 6 rows
idinteger · keyplantextregiontextsigned_up_attext
1proUS2025-01-01
2freeUS2025-01-02
3teamEU2025-01-02
4proIN2025-01-03
5freeEU2025-01-04

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT
  account_id,
  ROUND(100.0 * SUM(CASE WHEN status='success' THEN 1 ELSE 0 END)/NULLIF(COUNT(*),0),2) AS success_pct
FROM ai_requests
GROUP BY account_id;

Watch for: COUNT(*) in a LEFT JOIN makes an account with no requests appear to have one request.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Count successes and attempts. A success rate needs both numerator and denominator. NULLIF protects against dividing by zero.

    step-1.sql
    SELECT
      account_id,
      SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) AS successes,
      COUNT(*) AS attempts
    FROM ai_requests
    GROUP BY account_id;
  2. Turn counts into a rounded percent. Multiply by 100.0 for a real division, wrap the denominator in NULLIF(..., 0), then ROUND to two decimals.

    step-2.sql
    SELECT
      account_id,
      ROUND(100.0 * SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) AS success_pct
    FROM ai_requests
    GROUP BY account_id;

challenge 1

Return account_id and success_pct (0–100, rounded to 2 decimals) for accounts with requests.

Return account_idsuccess_pctany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.