In PostgreSQL, converted is an INTEGER column holding 0 or 1. This daily conversion-rate query shows 0 for almost every day, and 1 only on days where every trial converted. Why?
SELECT signup_date,
SUM(converted) / COUNT(*) AS conversion_rate
FROM trials
GROUP BY signup_date;Show the answer and explanation
Correct answer: D, Both SUM(converted) and COUNT() are integers, so / performs integer division and truncates; cast one side, e.g. SUM(converted)::numeric / COUNT().
Explanation SQL
In PostgreSQL (and SQL Server, and many other engines) integer / integer = integer, truncated toward zero. SUM(converted) returns bigint and COUNT(*) returns bigint, so 37 / 120 = 0. Only when every trial converts do you get n / n = 1.
Fixes:
SUM(converted)::numeric / COUNT(*) -- cast one operand
AVG(converted::numeric) -- mean of a 0/1 flag = rate
SUM(converted) * 1.0 / NULLIF(COUNT(*), 0) -- also guards against / 0Dialect differences matter:
| Engine | 7 / 2 |
|---|---|
| PostgreSQL, SQL Server | 3 (integer division) |
| BigQuery | 3.5 (INT64 / INT64 returns FLOAT64; use DIV(7, 2) for integer division) |
| Python 3 | 3.5 (// is floor division) |
In BigQuery you would typically write SAFE_DIVIDE(COUNTIF(converted = 1), COUNT(*)), which returns NULL instead of failing on division by zero.
Why the distractors are wrong: PostgreSQL truncates, it does not round, and ROUND applied after the division cannot recover lost decimals. Summing 0/1 flags cannot overflow: SUM of an INTEGER column already returns bigint, and PostgreSQL raises an error on overflow instead of wrapping around. NULLs in the denominator could bias the rate a little, but they cannot produce exactly 0 on nearly every day.
Interview tip: when a ratio metric looks suspiciously like 0 or 1, check integer division first; mention NULLIF or SAFE_DIVIDE for empty groups.