# How to avoid division by zero in SQL

Source: https://sqlstreak.com/sql/how-to/safe-division · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**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.

```sql
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 (both engines):

| 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 |

### 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.

```sql
SELECT 10 / NULLIF(0, 0) AS safe,
       COALESCE(10 / NULLIF(0, 0), 0) AS safe_or_zero,
       10 / 0 AS unsafe;
```

PostgreSQL: error: division by zero

SQLite:

| safe | safe_or_zero | unsafe |
| --- | --- | --- |
| NULL | 0 | NULL |

### Whole numbers lose the decimals

```sql
SELECT 7 / 2 AS whole, 7.0 / 2 AS decimal, ROUND(100.0 * 7 / 9, 1) AS pct;
```

Result (both engines):

| whole | decimal | pct |
| --- | --- | --- |
| 3 | 3.5 | 77.8 |

## How it works

- `NULLIF(COUNT(DISTINCT u.id), 0)`: Returns NULL when the count is 0, else the count.
- `100.0 * … / …`: Decimal division, then ROUND for display.

## Variations

### CASE instead of NULLIF

`CASE WHEN total = 0 THEN NULL ELSE part / total END` does the same, more wordily.

## Common mistakes

- `COALESCE` around 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.
