This error occurs when a SQL expression attempts to divide a number by zero, which is mathematically undefined and causes the query to fail.
Msg 8134, Level 16, State 1 Error: Divide by zero error encountered.
This error happens when a division operation in SQL includes a denominator that evaluates to zero. Since dividing by zero is undefined in mathematics, SQL Server (and most relational databases) will stop the query and throw this error.
It's a common issue when working with calculated fields like percentages or averages where the denominator might sometimes be zero due to filters, joins, or lack of data.
To prevent this, you need to proactively check whether the denominator is zero before dividing.
SUM()
or COUNT()
resulting in zeroQ: Why not just ignore the error and return NULL?
A: SQL Server throws an error by default. You must handle zero explicitly using CASE
or NULLIF()
to avoid it.
Q: Can I catch this error with TRY...CATCH?
A: Yes, but it's better to prevent it entirely using defensive SQL like CASE
or NULLIF()
. Relying on error handling slows performance.
Q: Does this happen in all databases?
A: Yes—PostgreSQL, MySQL, Oracle, and others will also fail or return errors when dividing by zero, though error messages may differ.