Back to Blog

Why Your AI Says This Product Is 100% of Revenue

Asked what share of revenue is Pro and got 100%. The query filtered to Pro first. SUM() OVER () then divided Pro by Pro. The other products were already gone, so the share of the remainder is the whole.

You ask: "What percent of revenue is Pro?" The AI says 100%. Pro is $40,000. The table is $100,000. The share is 40%.

SELECT SUM(amount) / SUM(SUM(amount)) OVER () AS share
FROM orders
WHERE product = 'Pro'

The WHERE runs first. The rows that reach the window are all Pro. SUM(amount) OVER () is $40,000, not $100,000. $40,000 / $40,000 is 1. The other products are not in the ratio at all.

The denominator has to be the set you named

"Percent of revenue" means percent of all of it, unless you said percent of Pro. A filter that chooses the product also chooses the total, when the total is computed in that same query.

-- share of all orders, filter only the numerator
SELECT
  SUM(amount) FILTER (WHERE product = 'Pro') * 1.0
  / NULLIF(SUM(amount), 0) AS pro_share
FROM orders

That is 0.40. The * 1.0 keeps Postgres and SQL Server from doing integer division and returning 0 for a smaller slice. FILTER keeps every order in the denominator and only Pro in the numerator.

This is not a grand total stamped on every row and then added up. There the total is right and a second sum multiplies it. Here the total is the wrong set, and the division is perfectly correct on that set. It is also not an average of daily rates. The arithmetic is one ratio. The population is the mistake.

How to catch it

SELECT
  SUM(amount) FILTER (WHERE product = 'Pro') AS pro,
  SUM(amount) AS everyone
FROM orders

If the AI's share is 1 and pro is less than everyone, the denominator was filtered down to Pro. Divide pro by everyone yourself. Do the same check any time a share, a mix, or a "percent of total" comes back as exactly 100% for something you know is not the whole business.

The prompt that heads this off

When I ask for a share of revenue, customers, or orders, the denominator
is the whole set I named, not the slice in the numerator. Do not put the
slice in WHERE and then divide by SUM() OVER (). Use FILTER or a
conditional SUM for the numerator, leave the denominator unfiltered, and
tell me both totals.

The short version

A WHERE before SUM() OVER () makes the window total the filtered rows. Pro divided by Pro is 100%. Compute the grand total without that filter, and put the product only in the numerator.


Read-only MCP gateway: mcpserver.design.

Related reading: