# division by zero

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


**Short answer:** At least one row divides by zero. Wrap the divisor in `NULLIF(divisor, 0)`: dividing by NULL gives NULL instead of an error. Add `COALESCE(…, 0)` if you'd rather show 0.

## The exact messages

- PostgreSQL: `ERROR: division by zero`

## How PostgreSQL prints it

```
ERROR:  division by zero
```

## Why it happens

### Ratios over groups that can be empty

Here dessert and drink have no meat items, so the count of meat items is 0 in those categories.

### Percentages of a total that can be zero

Conversion rates on days with no visitors, growth from a month with no revenue: anything divided by a count or sum.

## The broken query

```sql
SELECT category,
  SUM(price) / SUM(CASE WHEN vegetarian THEN 0 ELSE 1 END) AS per_meat_item
FROM menu_items
GROUP BY category;
```

## The fix

```sql
SELECT category,
  SUM(price) / NULLIF(SUM(CASE WHEN vegetarian THEN 0 ELSE 1 END), 0) AS per_meat_item
FROM menu_items
GROUP BY category;
```

`NULLIF(x, 0)` returns NULL when x is 0, and any division by NULL is NULL, so the problem rows show NULL instead of failing the whole query.

| category | per_meat_item |
| --- | --- |
| drink | NULL |
| dessert | NULL |
| pizza | 33.5 |
| side | 10.25 |

## What SQLite does instead

SQLite doesn't raise an error: dividing by zero returns NULL. That's safer, but it can hide the problem in reports.
