I need some help in finding why the following T-SQL statement returns 1 (true):

SELECT IIF( 0 = '', 1, 0)

I guess someone has change an ANSI option like SET ANSI_NULLS or something else that is causing the behavior.

My issue is that I am joining some values and in the final row set I have values which are joined by 0 and '' values, which is not correct.


That is just documented behavior. I don't think anyone messed with the settings.

See data type precedence on MSDN.

When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence.

As noted in the comments the empty string gets converted to 0 in any numeric type and to 1900-01-01 00:00:00.000 when converted to a date.

EDIT: I think your real problem is that your design is so that you have to join on fields of a different data type. The only way to get around this is to have a convert on your join clause which will hurt query performance. The main problem is probably with the schema design

EDIT: There was a lot of discussion in the comments that have been moved to chat. However illogical it may seem, converting an empty string to other data types produces arbitrary values.

This code:

SELECT CONVERT(datetime, '')

Produces this output:

1900-01-01 00:00:00.000

You could expect then that this behavior is consistent between other preceding datatypes and expect that converting 0 to a date would produce the same arbitrary value but it doesn't.



Explicit conversion from data type int to date is not allowed.

Because it's not a supported conversion


SELECT CONVERT(datetime, 0)


January, 01 1900 00:00:00

So yes, it's weird and arbitrary, but actually documented and explainable.

  • Comments are not for extended discussion; the conversation about this answer has been moved to chat. – Paul White Oct 10 '15 at 4:53
  • Is the behavior CAST('' AS INT) -> 0 documented somewhere? It would be nice if you add reference. – Salman A Dec 19 '17 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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