There are many times were we need to handle NULL and “empty” values in SQL Server. Note however, that there is a difference between a NULL and an “empty” value.
In this example we will examine the above cases and ways of handling it, when developing data processes in SQL Server.
Create a Sample Table with Some Data
Consider the following table:
CREATE TABLE [dbo].[table_A]
(
[id] [int] NOT NULL,
[name] [varchar](50) NULL,
CONSTRAINT [PK_table_A] PRIMARY KEY CLUSTERED([id] ASC)
) ON [PRIMARY];
GO
Let’s populate the table with some data:
INSERT INTO table_A(id,[name])
VALUES (1,'A'), (2,'B'), (3,''), (4,NULL);
GO
Note that the third record (id=3) contains an empty string for the column “name”.
Also note that the fourth (id=4) record contains a NULL value for the same column.
Strengthen you SQL Server development skills!
Enroll to the Course!
Sharpen your SQL Server database programming skills via a large set of tips on T-SQL and database development techniques. The course, among other, features over than 30 live demonstrations!
(Lifetime Access/ Live Demos / Downloadable Resources and more!)
Let’s see how can we handle the two above “special” cases.
First of all if we select all the records from table_A we will get:
select id, name from table_A;
GO
Result:
Handling the Issue of NULL and Empty Values
Then let’s try to handle the record having the NULL value and set as a new value the string “NewValue” for the result set of our select statement.
SQL Server provides 2 functions for doing this; (i) the ISNULL; and (ii) the COALESCE.
Even though the two functions are quite similar, still they have some differences:
(1) ISNULL takes only two parameters as input; (a) the expression to be checked and (b) the replacement value
(2) COALESCE takes N parameters as input (N>=2). By having N expressions as input parameters it returns the first expression that IS NOT NULL. If only all expressions are NULL it then returns a NULL value. It is like a more enhanced version of ISNULL.
Let’s try to handle the above scenario with these two functions.
Using ISNULL
--USE of ISNULL
SELECT id,ISNULL([name],'NewValue') FROM table_A;
GO
Result:
Using COALESCE
--USE of COALESCE
SELECT id,COALESCE([name],'NewValue','NewValue2') FROM table_A;
GO
Result:
Hmmm, we can see that even though for the record with id=4 we got the “NewValue” string instead of NULL, the record with id=3 still returned an empty string value.
In this case it seems that the ISNULL and COALESCE functions had no effect on the third record’s result. This was expected because that record does not contain a NULL value but an empty value instead. An empty value cannot be considered as a NULL of course.
So, how do we deal with this? How can we handle empty string values?
Unfortunately there is not a “magic” formula for that. The only suggestion is not to use empty strings but use NULL values instead which can be handled by the ISNULL, NULLIF and COALESCE functions.
Introducing a Custom Function for Handling Null and Empty Values
Additionally you can always create your own user-defined scalar-valued function that can deal with the issue of the empty string values. In my example, I created the following function and called it IsEmpty:
CREATE FUNCTION isEmpty
(
-- Input Parameters
@input as varchar(250),
@newValue varchar(250)
)
-- Output parameter
RETURNS varchar (250)
AS
BEGIN
-- First handle the case where the input value is a NULL
Declare @inputFiltered as varchar(250)
set @inputFiltered=ISNULL(@input,'')
-- The main logic goes here
RETURN (case rtrim(ltrim(@inputFiltered)) when '' then rtrim(ltrim(@newValue)) else rtrim(ltrim(@inputFiltered)) end)
END
GO
My function takes as input two parameters; (a) the input string and (b) the replacement string.
Then by using a combination of the ISNULL function and the CASE statement it handles both NULL and EMPTY string values. Though, the above user-defined function just handles strings and not any other expressions.
Now if we try running the IsEmpty function for the same example we get the following:
SELECT id, dbo.isEmpty([name],'NewValue') FROM table_a;
GO
Result:
Well, I guess that’s it! 🙂
You can find more information regarding the above mentioned built-in SQL Server functions that deal with NULLs on the following MSDN Library links: ISNULL, NULLIF, COALESCE.
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.
Views:19,269
5 thoughts on “Handling NULL and Empty Values in SQL Server”
gr8 article . heads off to you not bcoz what u did but bcoz what u did is needed by me a lot. i am searching and hitting towards blackhole of web but not getting that particular star(ur article). at last i found my moon. thanks again my dear friend .
thank you very very much … it is a new knowledge for me…
The simple things in life are often the best.
Can you please mek me under stand why these two below statements are different ..
The NULLIF returns NULL indeed for your example, however as NULLIF compared a single character (blank space), the ISNULL function replaces that one character with the first character of 'xyz'.
A way to overcome such issues is to use the COALESCE function: SELECT COALESCE(NULLIF('',''),'xyz')
Comments are closed.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Read More
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
gr8 article . heads off to you not bcoz what u did but bcoz what u did is needed by me a lot. i am searching and hitting towards blackhole of web but not getting that particular star(ur article). at last i found my moon. thanks again my dear friend .
thank you very very much … it is a new knowledge for me…
The simple things in life are often the best.
Can you please mek me under stand why these two below statements are different ..
SELECT ISNULL(NULLIF('','')/*Returns NULL*/,'xyz')
SELECT ISNULL(NULL,'xyz')
The NULLIF returns NULL indeed for your example, however as NULLIF compared a single character (blank space), the ISNULL function replaces that one character with the first character of 'xyz'.
For example, if you run:
SELECT ISNULL(NULLIF('aaa','aaa'),'xyz')
SELECT ISNULL(NULL,'xyz')
You will see that the output is the same.
A way to overcome such issues is to use the COALESCE function:
SELECT COALESCE(NULLIF('',''),'xyz')