sqlstreak

SQL error

division by zero

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

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

  • PostgreSQLERROR: division by zero
  • SQLiteNo error, but a silent surprise: see below.

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows 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.

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
SELECT category,
  SUM(price) / SUM(CASE WHEN vegetarian THEN 0 ELSE 1 END) AS per_meat_item
FROM menu_items
GROUP BY category;
Fixed
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.

The fix returns, PostgreSQL: 4 rows

categoryper_meat_item
drinkNULL
dessertNULL
pizza33.5
side10.25

The fix returns, SQLite: 4 rows

categoryper_meat_item
dessertNULL
drinkNULL
pizza33.5
side10.25

Experiment with it: PostgreSQL playground·SQLite playground

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.

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: NULL in SQL: IS NULL, COALESCE and the traps.