SQL Error: division by zero / Divide by zero error encountered
An expression divided by a value that was 0 for at least one row.
Meaning
PostgreSQL and SQL Server raise an error; MySQL returns NULL (or errors in strict mode with ERROR_FOR_DIVISION_BY_ZERO). Ratios, averages and percentages over empty groups are the usual sources.
Common causes
- Ratio with a zero denominator (no orders, no visits)
- Average/percentage computed for empty groups
- Data with unexpected zeros
⚡ Quick fix
- Wrap the denominator with
NULLIF(x, 0) - Use CASE to return 0 or NULL explicitly
- Filter out zero rows when they aren’t meaningful
Detailed fix by platform
SQL
- NULLIF guard:sql
SELECT campaign, clicks * 100.0 / NULLIF(impressions, 0) AS ctr_percent FROM campaign_stats;
How to diagnose
- Expression — Which division?
- Rows — Which rows have a 0 denominator?
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 2 Oct 2026