Click here to Skip to main content
15,881,380 members
Articles / Programming Languages / SQL
Tip/Trick

SQL - Now you see me, now you don't

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
14 May 2012CPOL 7.7K   4   1
ISNULL - COALESCE

Introduction

SQL Server, undoubtedly my favourite Microsoft product, but a seasoned baseball pitcher will be impressed by the curve balls it can produce.

Using the code 

Execute the following script:

SQL
declare @var1 VARCHAR(1)
SET @var1 = '2'
SELECT ISNULL(@var1, 1)
SELECT ISNULL(@var1, -1)
SELECT COALESCE(@var1, -1)
SET @var1 = NULL
SELECT ISNULL(@var1, 1)
SELECT ISNULL(@var1, -1)
SELECT COALESCE(@var1, -1)

Sure, it is easy to see the culprit, but now read this thinking that @var1 is a column defined in a table, so it is not so obvious what the length of the column/variable is.

  • ISNULL – replaces the NULL value with the given replacement.
  • COALESCE – returns the first not NULL expression in the argument list.

When reading the MSDN topic on T-SQL ISNULL it does say that it returns the SAME type as the checked expression, the value is IMPLICITLY converted to the checked expression’s type when the two types differ.

The interesting part is that the conversion does not procedure a String or binary data will be truncated error?

This does not prove that COALESCE is better than ISNULL, all it is saying: know the animal you are working with.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Kohde.io
South Africa South Africa
I escaped from the mental hospital on 25th June and was captured by a zookeeper. Escaped from the zoo on 15th July and killed the zoo guard in the attempt. So now I just eat bananas and hang out on the Code Project.

Comments and Discussions

 
GeneralThoughts Pin
PIEBALDconsult14-May-12 9:30
mvePIEBALDconsult14-May-12 9:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.