# SQL Error: division by zero / Divide by zero error encountered

**Code:** `Division by zero` · **Category:** SQL · **Seen on:** PostgreSQL, MySQL, SQL

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

1. Wrap the denominator with `NULLIF(x, 0)`
2. Use CASE to return 0 or NULL explicitly
3. Filter out zero rows when they aren’t meaningful

## Detailed fix by platform

### SQL

1. NULLIF guard:

```sql
SELECT campaign, clicks * 100.0 / NULLIF(impressions, 0) AS ctr_percent
FROM campaign_stats;
```


## How to diagnose

1. **Expression** — Which division?
2. **Rows** — Which rows have a 0 denominator?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/sql/division-by-zero)
