Home Forums SQL Server 2005 T-SQL (SS2K5) Division by zero on a SQL Instance while a different Instance run correctly RE: Division by zero on a SQL Instance while a different Instance run correctly

  • Hi

    A curiosity : In my case this strange behaviour helps to find a potential data issue but speaking in general term shouldn't it be considered an error of the DB Engine ?

    That's exactly what I thought when I first came across this a few years ago! However, SQL is designed as a declarative language so that the statements you write only really define what data you want to manipulate, but intentionally do not define HOW the database should do it.

    This has huge advantages in terms of optimisation, but means that you cannot make any assumptions about the order of execution of the logic of your statements.

    This 'undefined behaviour' even goes so far that you cannot rely on an expression like (a = b) and (c = d) being evaluated left to right and short-circuited. If you must define the order of evaluation, the normal approach is using CASE (as you did)

    SELECT * FROM t

    WHERE (a<>0) and (b/a=2) -- Might fail with divide by zero

    -- could be rewritten as

    SELECT * FROM t

    WHERE (CASE WHEN a<>0 THEN b/a ELSE null END) = 2

    Best description of this I've found is in the Short Circuit article by Itzik Ben-Gan (whose stuff is always worth reading).