Full answer
A per-day report divides revenue by the number of orders. On a day with no orders, the denominator is zero.
PostgreSQL stops the whole query:
CREATE TABLE day_stats (day TEXT PRIMARY KEY, revenue INTEGER, orders INTEGER);
INSERT INTO day_stats VALUES ('2026-03-01', 310, 4), ('2026-03-02', 0, 0), ('2026-03-03', 250, 3);SELECT day, revenue / orders AS per_order FROM day_stats ORDER BY day; -- error on purposeError: division by zeroSQLite does not raise an error. It returns NULL for any division by zero:
SELECT day, revenue / orders AS per_order FROM day_stats ORDER BY day;| day | per_order |
|---|---|
| 2026-03-01 | 77 |
| 2026-03-02 | NULL |
| 2026-03-03 | 83 |
Relying on that SQLite behaviour is risky, because the same query fails after a move to PostgreSQL. NULLIF makes the intent explicit on every engine:
SELECT day,
ROUND(1.0 * revenue / NULLIF(orders, 0), 2) AS per_order
FROM day_stats
ORDER BY day;| day | per_order |
|---|---|
| 2026-03-01 | 77.5 |
| 2026-03-02 | NULL |
| 2026-03-03 | 83.33 |
PostgreSQL accepts the guarded query:
SELECT day,
ROUND(1.0 * revenue / NULLIF(orders, 0), 2) AS per_order
FROM day_stats
ORDER BY day;| day | per_order |
|---|---|
| 2026-03-01 | 77.50 |
| 2026-03-02 | NULL |
| 2026-03-03 | 83.33 |
Whether the result for an empty day should be NULL or 0 is a product decision. NULL says "not defined". A 0 says "nothing earned per order", which can mislead a chart. If the dashboard needs a number, add COALESCE(..., 0) on the outside, and label it clearly.
Compare the first SQLite result with the guarded one. Without 1.0 *, integer division truncated 77.5 to 77 and 83.33 to 83 before anyone noticed.
CREATE TABLE day_stats (day TEXT PRIMARY KEY, revenue INTEGER, orders INTEGER);
INSERT INTO day_stats VALUES ('2026-03-01', 310, 4), ('2026-03-02', 0, 0), ('2026-03-03', 250, 3);
SELECT day, revenue / orders AS per_order FROM day_stats ORDER BY day;
SELECT day,
ROUND(1.0 * revenue / NULLIF(orders, 0), 2) AS per_order
FROM day_stats
ORDER BY day;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- x / NULLIF(y, 0) returns NULL instead of failing
- PostgreSQL raises an error on division by zero; SQLite returns NULL
- COALESCE outside the division supplies a default if needed
- Watch for integer division in the same expression
Common mistakes
- Testing on SQLite, where division by zero is silent, and failing in production
- Defaulting undefined ratios to 0 without telling the reader
Follow-ups
- How would you compute conversion rate per campaign with zero visits on some days?
- Why does showing NULL instead of 0 matter on a dashboard?
Tips
- Mention the engine difference; it shows you have moved queries between databases