When you need it
"What percent of orders were refunded?", "click-through rate by campaign", "share of revenue from each channel", "cost per signup". Words that signal it: "percent", "rate", "share", "ratio", "per", "proportion", "out of".
Most of the work is deciding what goes on the bottom. Say it in a sentence: "refunded orders divided by all orders placed". The numerator and the denominator must count the same kind of thing over the same set of rows.
The shape of the query
select group_col,
round(100.0 * sum(<numerator>) / nullif(sum(<denominator>), 0), 1) as pct
from ...
group by group_col;Step by step:
- Build the numerator and denominator at the same grain, using aggregates side by side.
- Multiply by
100.0(with the decimal point) before dividing so you never do integer division. - Wrap the denominator in
NULLIF(x, 0)so an empty group gives NULL, not an error. - Round last.
select c.campaign_name,
sum(d.clicks) as clicks,
sum(d.impressions) as impressions,
round(100.0 * sum(d.clicks) / nullif(sum(d.impressions), 0), 2) as ctr_pct
from campaigns c
join ad_daily d on d.campaign_id = c.campaign_id
group by c.campaign_name
order by ctr_pct desc, c.campaign_name;A share of a total uses a window over the whole result, so no second query is needed:
select channel,
count(*) as orders,
round(100.0 * count(*) / sum(count(*)) over (), 1) as pct_of_orders
from orders
where status = 'completed'
group by channel
order by orders desc, channel;sum(count(*)) over () sums the grouped counts across all rows of the result. The aggregate runs first, then the window runs on its output.
Traps interviewers look for
- Integer division. In PostgreSQL, SQL Server and Redshift,
3 / 4is0. Cast one side or multiply by1.0first. Writing100 * a / balso works whenais an integer, buta / b * 100returns 0. - Divide by zero. A group with no impressions crashes the query in PostgreSQL.
NULLIF(denominator, 0)returns NULL instead. Decide with the prompt whether the report should show NULL or 0. - A rate of rates. The average of per-row percentages is not the overall percentage. Sum the numerator, sum the denominator, divide once.
- Wrong denominator. "Percent of customers who ordered" has all customers on the bottom, not just those with orders. A join that drops the non-buyers will quietly make every rate 100 percent.
- Mismatched filters. If the numerator counts completed orders but the denominator counts all orders, say so. If they should match, apply one filter to both.
- Rounding too early. Round the final value only. Rounded parts compound the error.
Variations
- Conditional numerator.
count(*) filter (where status = 'refunded')orsum(case when ... then 1 else 0 end)overcount(*). See the conditional aggregation lesson. - Percent of group total.
sum(x) over (partition by category)as the denominator. - Percent change.
(new - old) / nullif(old, 0), covered under period over period. - Per-unit metrics. Revenue per customer, cost per click: same shape, different denominator.
- Basis points and per-thousand. Multiply by 10000 or 1000 instead of 100 when the prompt asks.
In other warehouses
- Snowflake and BigQuery return a decimal or float from
/even for two integers, so3 / 4is0.75. Code that works there will return 0 on PostgreSQL, SQL Server or Redshift. Always write the100.0 *form. - BigQuery has
SAFE_DIVIDE(a, b), which returns NULL on a zero denominator. Snowflake hasDIV0(a, b)(returns 0) andDIV0NULL. - SQL Server needs
CAST(x AS decimal(10,2))or1.0 *to avoid integer division, and errors on divide by zero just like PostgreSQL. - MySQL returns
NULLfor division by zero by default instead of raising an error.