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 · key | account_idinteger | modeltext | requested_attext | input_tokensinteger | output_tokensinteger | statustext |
|---|---|---|---|---|---|---|
| 1 | 1 | swift | 2025-01-01 10:00:00 | 1000 | 200 | success |
| 2 | 1 | reason | 2025-01-02 11:00:00 | 2000 | 600 | success |
| 3 | 2 | swift | 2025-01-02 12:00:00 | 500 | 0 | error |
| 4 | 3 | reason | 2025-01-02 13:00:00 | 8000 | 2000 | success |
| 5 | 3 | swift | 2025-01-03 14:00:00 | 4000 | 1000 | success |
showing 5 of 12 rows
ai_accounts4 columns · 6 rows
| idinteger · key | plantext | regiontext | signed_up_attext |
|---|---|---|---|
| 1 | pro | US | 2025-01-01 |
| 2 | free | US | 2025-01-02 |
| 3 | team | EU | 2025-01-02 |
| 4 | pro | IN | 2025-01-03 |
| 5 | free | EU | 2025-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.
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.
Count successes and attempts. A success rate needs both numerator and denominator. NULLIF protects against dividing by zero.
step-1.sqlSELECT account_id, SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) AS successes, COUNT(*) AS attempts FROM ai_requests GROUP BY account_id;
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.sqlSELECT 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;