4

In the past I've seen use of something such as

SELECT ISNULL(NULLIF(Field1, ''), 'NewValue')

to tersely get a fallback value.

However, since the advent of CASE in TSQL, we've favored something more like

SELECT CASE Field1 WHEN '' THEN 'NewValue' ELSE Field1 END

Is one going to perform better than the other? What other reasons would there be to choose one over the other?

GaTechThomas
  • 673
  • 1
  • 6
  • 13
  • 1
    Similar question to [Performance difference for COALESCE versus ISNULL?](http://dba.stackexchange.com/q/4274/3690). The same points about possible different result datatypes and possible double evaluation of the expression with `CASE` still apply. – Martin Smith Oct 08 '12 at 20:35

1 Answers1

9

The primary difference between your examples is that the latter does not replace NULL with your default value.

With regard to performance, you will generally need to try very hard to find a measurable difference (in the order of a few seconds over millions of rows). Search for performance measures for isnull, coalesce, and case--you'll find lots of blog posts about them.

The common voice I've heard is that you should use the structure that feels the most readable for your team, and any time you get the feeling that it might not be as performant as it could be, test it. Run it both ways, and compare the time it takes to complete, and compare the execution plans.

SQLFox
  • 1,534
  • 12
  • 23
  • Good point about the latter not replacing NULL with default. Fortunately the case I had in mind references a non-nullable column. – GaTechThomas Oct 08 '12 at 20:53
  • 1
    @GaTechThomas so it's not nullable, but it allows zero-length strings which seems to indicate the same thing? What's the point of not allowing NULLs if you can inject a blank string in there? – Aaron Bertrand Oct 08 '12 at 21:51
  • @AaronBertrand It's varchar, which defaults to being rtrimmed. Unfortunately I don't know the design decisions behind this field. – GaTechThomas Oct 09 '12 at 16:12
  • @GaTechThomas I think you missed my point. Why is an empty string allowed in a non-NULLable column (whether "empty string" means 0 spaces, 10 spaces, and whether or not it is trimmed)? – Aaron Bertrand Oct 09 '12 at 17:07
  • @AaronBertrand Unfortunately I don't know the design decisions behind this field. My guess is that performance gains were intended in not allowing NULLs. However, IIRC, the field would need to be fixed width in order for the performance gain to apply, so the varchar wouldn't gain much. – GaTechThomas Oct 09 '12 at 18:33
  • @AaronBertrand Maybe it's part of a composite primary key? – NReilingh Mar 08 '17 at 19:05