SQL how-to
How to avoid division by zero in SQL
Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)
Short answer
Wrap the divisor in NULLIF(divisor, 0): a zero becomes NULL, and dividing by NULL gives NULL instead of an error. Add COALESCE(…, 0) if you'd rather show 0, and multiply by 100.0 when both numbers are whole.
The task: Divide one number by another without an error when the divisor is 0, and without losing the decimals.
A conversion rate that survives zero
Subscribers per sign-up source, where a made-up source with no users would divide by zero.
SELECT u.source,
COUNT(DISTINCT u.id) AS users,
COUNT(DISTINCT s.user_id) AS subscribers,
ROUND(100.0 * COUNT(DISTINCT s.user_id) / NULLIF(COUNT(DISTINCT u.id), 0), 1) AS conversion_pct
FROM users u
LEFT JOIN subscriptions s ON s.user_id = u.id
GROUP BY u.source
ORDER BY u.source;Result (PostgreSQL and SQLite, identical): 4 rows
| source | users | subscribers | conversion_pct |
|---|---|---|---|
| ad | 57 | 18 | 31.6 |
| friend | 91 | 39 | 42.9 |
| podcast | 55 | 14 | 25.5 |
| search | 97 | 29 | 29.9 |
Try it: PostgreSQL playground · SQLite playground
How it works
- 1
NULLIF(COUNT(DISTINCT u.id), 0)Returns NULL when the count is 0, else the count.
- 2
100.0 * … / …Decimal division, then ROUND for display.
More examples
What zero does, with and without NULLIF
SQLite returns NULL for a division by zero; PostgreSQL stops with an error. With NULLIF both return NULL.
SELECT 10 / NULLIF(0, 0) AS safe,
COALESCE(10 / NULLIF(0, 0), 0) AS safe_or_zero,
10 / 0 AS unsafe;PostgreSQLERROR: division by zero
SQLite: 1 row
| safe | safe_or_zero | unsafe |
|---|---|---|
| NULL | 0 | NULL |
Try it: PostgreSQL playground · SQLite playground
Whole numbers lose the decimals
SELECT 7 / 2 AS whole, 7.0 / 2 AS decimal, ROUND(100.0 * 7 / 9, 1) AS pct;Result (PostgreSQL and SQLite, identical): 1 row
| whole | decimal | pct |
|---|---|---|
| 3 | 3.5 | 77.8 |
Try it: PostgreSQL playground · SQLite playground
Variations
CASE instead of NULLIF
CASE WHEN total = 0 THEN NULL ELSE part / total END does the same, more wordily.
Common mistakes
COALESCEaround the divisor (x / COALESCE(y, 1)): it hides missing data behind a made-up 1.Integer division:
COUNT(*) / COUNT(*)is 0 or 1. Multiply by 100.0 or 1.0 first.Relying on SQLite's NULL: the same query raises an error in PostgreSQL.
PostgreSQL and SQLite
PostgreSQL raises division by zero; SQLite quietly returns NULL. NULLIF makes both behave the same, which the second example shows.
Official documentation
Go deeper
- Guide: Data cleaning in SQL
- Practice: SQL data cleaning practice: 6 exercises with answers
- Lesson: Empty, NULL and defaults (Pro)
Make it stick in five minutes a day
“Empty, NULL and defaults” teaches this step by step on a real database, with instant feedback. Part of sqlstreak Pro; the first lessons are free.