skip to content

A revenue report's totals miss finance's by a few cents and its conversion-rate column is always 0; how do you diagnose and fix both in SQL?

level: seniorimportance: should knowfreq 46%

answer

  1. two symptoms, two different causes
  2. check operand types first
  3. reproduce one mismatched document
  4. direction of the difference is a clue
  5. ask finance for its rule

basics

~20 s

The always-0 column is integer division: cast one operand to DECIMAL before dividing and guard the denominator with NULLIF. The cents usually come from rounding: compare your rounding stage, tie rule and any truncation with finance's on one mismatched document.

solid answer

~40 s

I'd treat them as two bugs. A rate that is always 0 means integer operands on an integer-dividing engine, so I'd confirm the types and write `CAST(conversions AS DECIMAL(12,6)) / NULLIF(visits, 0)`, with the cast on the operand, not around the quotient. For the cents, I'd reproduce one mismatched document line by line against finance's figures. Rounding each line and rounding the total can legitimately differ. Scattered differences suggest the rounding stage, always-low differences on positive amounts suggest truncation, and differences only on exact halves suggest a tie rule. I'd also look for a float or an early cast in the chain, then agree the rule with finance and put it in one shared expression.

code

sql · 3 lines
sql
SELECT report_day,
       ROUND(CAST(conversions AS DECIMAL(12,6)) / NULLIF(visits, 0), 4) AS conversion_rate
FROM daily_funnel;

go deeper

for a junior

Recognise that a rate which is always 0 means integer division, and fix it by making one operand decimal before dividing. Add a guard for a zero denominator.

for a middle

Explain why casting around the quotient fails, and show with a small example how rounding per line and rounding a total can differ by a cent with no bug in either.

for a senior

Lead with evidence: reproduce one document at the finest grain, read the sign and shape of the differences, match them to stage, truncation, tie rule or float, and confirm the rule with finance before changing anything.

for a principal

Own the rule rather than the single fix. Agree with finance where rounding happens and which tie rule applies, keep it in one shared expression, and reconcile on a schedule, since reports written separately will drift apart.

## Two symptoms, two causes The report looks like one problem and is two. The rate column fails completely and identically on nearly every row, which points to a type problem. The totals fail by tiny amounts on some rows, which points to a rule problem. Diagnose them separately, because a fix for one does nothing for the other: moving everything to `DECIMAL` repairs the rate and can still leave you a cent away from finance. ## The rate that is always 0 The steps are short because the behaviour is deterministic. 1. **Check the operand types.** If `conversions` and `visits` are integers and the engine divides integers (PostgreSQL, SQL Server, SQLite), every value below 1 truncates to 0. 2. **Check the outliers.** A row where every visit converted returns exactly 1. Seeing only 0s and the occasional 1 all but confirms it. MySQL and Oracle do not divide integers this way, so if the query was ported from one of them, you have your explanation. 3. **Fix the operand.** Use `CAST(conversions AS DECIMAL(12,6)) / visits`. A `CAST` or `ROUND` around the finished quotient receives the 0 and keeps it. On SQLite a `DECIMAL` cast leaves an integer unchanged, so cast to `REAL` there. 4. **Guard the denominator.** A day with no visits raises an error on PostgreSQL and SQL Server, and returns `NULL` on MySQL and SQLite. `NULLIF(visits, 0)` makes the rate `NULL` on every one of them. A rate over zero visits is undefined rather than zero, so leaving it `NULL` is usually the honest output. Turning it into 0 for display is a decision for whoever owns the report. ## The cents Do not start by reading the query. Start with evidence. 1. Choose a single document or day that disagrees, and get finance's figures for it at the finest grain they have. 2. Compute your figure at that grain, keeping every intermediate column visible. 3. List the differences with a threshold, as in `WHERE ABS(report_amount - finance_amount) >= 0.01`. 4. Read the **pattern** of those differences, because the pattern narrows the cause. | Pattern of differences | Likely cause | Check | |---|---|---| | Scattered both ways, small | Rounding at a different stage | Do you round per line and they per document, or the reverse? | | Always low on positive amounts | Truncation where finance rounds | `TRUNC`, `ROUND(x, d, 1)`, or a cast that truncates | | Only where the next digit is exactly 5 | A different tie rule | Finance uses half-even, `DECIMAL` ties here go away from zero | | Noise with no pattern, on many rows | A float in the chain | Any `FLOAT` column, cast or literal before `ROUND` | | Grows with quantity | An early cut | A cast to two decimals before multiplying, or a divide before a multiply | The **rounding stage** is a frequent cause, and it is not an engine defect. Three lines of exactly 0.335 give 1.02 when each is rounded and then added, and 1.01 when their total of 1.005 is rounded. Both are correct arithmetic. At most one matches the books. ## Fixing it - **Agree the rule first.** The stage and the tie rule are business decisions, often driven by tax or invoicing rules, so get finance to state them. Do not reverse-engineer them from a matching month. - **Compute in an exact type throughout,** and remove any float operand, since otherwise rounding starts from an approximation. - **Multiply before dividing,** and round only once at the agreed stage, so no intermediate cut gets magnified. - **Keep the rule in one expression or view.** A report and a dashboard each carrying their own rounding will disagree with each other next. - **Test the awkward values:** an exact tie, a negative refund line (on an exact type, -0.125 rounds to -0.13 at two places on PostgreSQL), a zero denominator, and a document whose rounded lines differ from its rounded total. ## Knowing when to stop A remaining difference is not automatically a bug. If finance rounds per invoice and the report legitimately shows a per-day view, then a small gap is the correct answer and should be labelled, or the report should be rebuilt from the invoice-level figures. Stating that clearly, with the reconciled example in hand, is usually what closes the issue.

  • How do you tell a rounding-stage mismatch from a truncation bug?
    Look at the sign of the differences. Truncation always moves a positive amount down, so report-minus-finance is consistently negative on positive amounts. A rounding-stage mismatch scatters both ways, because each line can round up or down. Confirm by recomputing the same document at both stages and seeing which reproduces finance's figure exactly.
  • Why isn't WHERE visits <> 0 AND 1.0 * conversions / visits > 0.1 a reliable divide-by-zero guard?
    SQL does not promise left-to-right evaluation of `AND`, so an engine may evaluate the division first and fail on a zero row. Put the guard inside the expression that divides, with `NULLIF(visits, 0)` or a `CASE`. The comparison then sees `NULL`, and the row is filtered out without any division by zero.
  • Should the rate show 0 or NULL on a day with no visits?
    `NULL` is the accurate default, since zero visits gives no rate at all, and a 0 would claim that visitors came and none converted. It also keeps those days from dragging down any later comparison. Displaying a dash or a 0 is fine as a presentation choice, as long as the report's owner has agreed to it.

  • The rate is a formatting problem, so ROUND(conversions / visits, 4) will fix it.
  • CAST(conversions / visits AS DECIMAL(10,4)) restores the lost rate.
  • A few cents is untraceable noise that every report has to live with.
  • Rounding each line and rounding the total always give the same figure.
  • Moving every column to DECIMAL guarantees the report will match finance.
  • COALESCE(visits, 0) guards the denominator against a divide by zero.