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?

1

1 Answer 1

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.

6
  • Good point about the latter not replacing NULL with default. Fortunately the case I had in mind references a non-nullable column. Oct 8, 2012 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? Oct 8, 2012 at 21:51
  • @AaronBertrand It's varchar, which defaults to being rtrimmed. Unfortunately I don't know the design decisions behind this field. Oct 9, 2012 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)? Oct 9, 2012 at 17:07
  • 1
    @AaronBertrand Maybe it's part of a composite primary key?
    – NReilingh
    Mar 8, 2017 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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