Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Actually I've got bad news. The where clause should be run before the select but for reasons of, I guess cheating at the benchmarks, oracle doesn't do that and MSSQL followed that. It is particulary nasty as it mostly works, so this (CTE to not clutter your schema)

  with data as
  (
   select *
   from
   (
    values(1), (2), (0), (4)
   ) as abc(d)
  )
  select 1 / d
  from data
  -- where d <> 0
gives divide by zero. If you uncomment the where it then seems to work correctly.

Well it doesn't. You cannot rely on this for MSSQL2005 or later. When the expressin grows more complex it blows up - I am saying this from losing days of work by finding out the hard way.

I'll repeat myself, the expressions in the select and that in the where can be evaluated in parallel. Thank you Microsoft.

Microsoft's solution to this is to expect the programmer to deal with it by skipping the evaluation of the expression

  with data as
  (
   select *
   from
   (
    values(1), (2), (0), (4)
   ) as abc(d)
  )
  select case when d <> 0 then 1 / d else null end
  from data
  where d <> 0;
The case prevents any possible division by zero.

I've had this behaviour confirmed by Microsoft, and the supposed fix was their solution.

Not coincidentally I'm looking at learning postgres. For this and other reasons I don't want to work with MSSQL any more.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: