0

I fired a query as

SELECT * FROM tblEmp WHERE emp_id = 9737  AND mgr_id = NULL

and it dodn't return any value. Till yesterday it was doing so. What might be changed? We many people work on same server so there is chance that some one changed something.

To get the result I have to fire

SELECT * FROM tblEmp WHERE emp_id = 9737  AND mgr_id IS NULL

which is giving proper output.

Since I am using this query in .Net I am afraid if it breaks when settings are reset as previous one. Will it?

1
  • 1
    AFAIK your original query should never have returned anything. The reason for this is that comparing something to NULL using equals is always NULL. And emp_id = 9737 AND NULL is also unknown. Lesson learned, use IS NULL and IS NOT NULL when comparing to NULL. May 12, 2017 at 5:32

2 Answers 2

6

Setting the ANSI_NULLS feature of SQL Server to OFF will let you write mgr_id = NULL and evaluate it to TRUE.

However, it's bad practice to compare NULLs this way. Most RDBMSs won't allow it, most DBAs won't write queries that way, and the ANSI_NULLS setting has been deprecated for quite awhile and will be forced ON in the future.

4
  • Nice explanation +1 ... and the only one which explains how any results could have been coming through May 12, 2017 at 5:33
  • Thanks for the descriptive answer. But what if ansi_nulls set to off again. will mgr_id is null will work as same?
    – Imad
    May 12, 2017 at 5:51
  • @Imad The ANSI_NULLS setting will default to whatever the setting is on the database. You can modify the default setting using ALTER DATABASE SET ANSI_NULLS to default it off. You can use sp_configure user options to configure it per-user. Otherwise, you will need to issue SET ANSI_NULLS OFF; each session with, for example, ExecuteNonQuery();.
    – Bacon Bits
    May 12, 2017 at 17:39
  • @Imad To be perfectly clear, I never set this setting off, so I'm not 100% certain of what you need to set to force it off for all connections. It's entirely possible for a database provider to set the value on manually. As far as I'm aware, there's no way to prohibit a connection from ever enabling it.
    – Bacon Bits
    May 12, 2017 at 17:41
0

Null is not a value and so you cannot use = operator. You should use is null function for it to work.

Not the answer you're looking for? Browse other questions tagged or ask your own question.