SQL Server throws division by zero exception in calculation

I’m running into a division by zero problem when executing this SQL query. The error happens when I try to run this mathematical calculation in SQL Server. Here’s the code that’s causing the issue:

select ((((45678900.0000000000)+(62341200.0000000000))/2)/((18765400.0000000000)-(29876540.0000000000)+(11111140.0000000000)))*365

I’ve been trying to figure out why this happens since the numbers look fine to me. The calculation involves adding two large decimal numbers, dividing by 2, then dividing by another expression that subtracts and adds some values, and finally multiplying by 365. Has anyone encountered this before? What’s the best way to handle this kind of division error in SQL Server?

nullif() is perfect for this! Just wrap your denominator like: nullif(((18765400.0000000000)-(29876540.0000000000)+(11111140.0000000000)), 0) - it returns null instead of crashing when you hit zero. Way cleaner than case statements.

Your denominator equals zero - that’s what’s causing the error. When you calculate (18765400.0000000000 - 29876540.0000000000 + 11111140.0000000000), it comes out to exactly zero, which breaks the division. You need to add a check using CASE or NULLIF. Here’s how I’d fix it: select case when ((18765400.0000000000)-(29876540.0000000000)+(11111140.0000000000)) = 0 then null else ((((45678900.0000000000)+(62341200.0000000000))/2)/((18765400.0000000000)-(29876540.0000000000)+(11111140.0000000000)))*365 end This returns null instead of crashing when the denominator hits zero. Your query will run without errors and handle the edge case cleanly.

hey, have you tried isolating that denominator? it might be hitting zero, which causes the error. run just that part, 18765400 - 29876540 + 11111140, and see what you get. could help pinpoint the issue!