Skip to content

Ratios and percentages

Compute shares, rates and percentages correctly, with the right denominator, no integer division and no divide by zero.

Practise: 15 questions

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:

  1. Build the numerator and denominator at the same grain, using aggregates side by side.
  2. Multiply by 100.0 (with the decimal point) before dividing so you never do integer division.
  3. Wrap the denominator in NULLIF(x, 0) so an empty group gives NULL, not an error.
  4. 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

Variations

In other warehouses

Practise ratios and percentages