← All writing

Handle an empty SUM result without confusing it with unknown data

MySQL 8.0+ / InnoDBSources checked 2026-09-14

A dashboard with no invoices shows a blank balance because SUM over no matching rows returns NULL. For a known empty set, displaying zero can be appropriate, but that choice should not conceal a failed query or missing source data.

Normalize the known empty aggregate

SELECT COALESCE(SUM(amount), 0) AS total
FROM invoices
WHERE tenant_id = 42;

The sample assumes all selected amounts are comparable and the query succeeded. COALESCE changes a null result into zero. It does not establish that an upstream import is complete or that the dashboard includes every invoice.

Keep freshness separate from value

A dashboard can show zero together with a “last refreshed” timestamp. If data collection failed, show the failure or stale state rather than replacing it with a reassuring zero. Unknown and known-empty are different operational states.

If a grouped query has no groups, it may return no rows at all rather than a row containing zero. Handle the expected result shape as well as the aggregate value.

Test no matching invoices, a zero-value invoice, positive values, and an upstream failure in the application path. Verify the UI distinguishes a valid empty result from unavailable data. This distinction is particularly important for stock, balances, and queue counts, where a false zero can cause a person to take the wrong action.

Reference

Official documentation.