SQL Error Guide

SQL Error: Division By Zero (Fix + Examples)

Fix the SQL "division by zero" error. Learn what causes it and see examples of how to resolve it.

Getting the "division by zero" error in SQL? This guide explains what causes this error and how to fix it with practical examples.

What Causes This Error?

The division by zero error (22012) occurs when:

  • Dividing by a column that contains zero values
  • Calculating percentages without handling zero totals
  • Aggregate functions returning zero in denominator

How to Fix It

  1. Use NULLIF(divisor, 0) to convert zero to NULL (returns NULL instead of error).
  2. Use CASE WHEN to check for zero before dividing.
  3. Filter out zero values with WHERE clause.
  4. Use COALESCE to provide default value when result is NULL.

Example: Wrong vs Correct

❌ Code That Causes the Error

SELECT revenue / quantity AS unit_price FROM orders; -- Error: division by zero when quantity = 0

✅ Corrected Code

SELECT revenue / NULLIF(quantity, 0) AS unit_price FROM orders; -- Correct: returns NULL instead of error when quantity = 0

Quick Checklist

  • [ ] Verify column/table names are spelled correctly
  • [ ] Check data types match expected values
  • [ ] Review query syntax for missing keywords
  • [ ] Ensure referenced tables/columns exist

Related SQL Errors

If you're troubleshooting SQL errors, you might also encounter:

Related Content

From Our Blog

Still stuck?

Practice SQL in our sandbox environment with instant error feedback.