To replace null with a specified replacement value, we can use any of the following:
- ISNULL() function
- CASE statement
- COALESCE() function
For the demo we will be using this tblPerson table.
In the table we have the three columns P_Id, Name and Gender. P_Id is the primary column of this table.
The following is the query for creating this table.
- CREATE DATABASE db_ReplaceNull;
-
- USE db_ReplaceNull;
-
- CREATE TABLE tblPerson(
- P_Id INT CONSTRAINT pk_Id PRIMARY KEY,
- Name NVARCHAR(50),
- Gender NVARCHAR(10)
- );
-
- INSERT INTO tblPerson VALUES (101,'Sam','Male'),(102,'Sara','Female'),(103,'Michael',null),
- (104,null,null),(105,null,'Female'),(106,'Max',null),(107,'Aiden Pearce','Male');
When I execute this query.
- SELECT P_Id,Name,Gender FROM tblPerson;
I get the following records.
The preceding query returns many columns with null values. Now let's say there is a requirement to replace all these null values with meaningful text. For example, replace null with "no name" for the name column and replace null with "no gender" for the gender column.
1. ISNULL Function
The ISNULL Function is a built-in function to replace nulls with specified replacement values.
To use this function, all you need to do is pass the column name in the first parameter and in the second parameter pass the value with which you want to replace the null value.
So, now all the null values are replaced with No Name in the Name column.
Now let's do the same for the Gender column.
Pass the column Gender in the parameter of the ISNULL function and in the second parameter pass the replacement value.
2. CASE statement
To begin a case statement we use:
CASE
If the column value is null then that value will be replaced with the "replacementValue".
If the column value is not null then it will print the following column value:
To end the case, use "end".
3. COALESCE() function
The COALESCE() function returns the first NON NULL value.
If you look at this table.
There are two nulls in the Name column and three nulls in the Gender column and with the help of COALESCE we will get the first non-null value from both of the columns.
How to use COALESCE function
Pass the column names separated by commas as a parameter.
- SELECT P_Id, COALESCE(Name,Gender) AS [First Non-Null Value] FROM tblPerson;
When we execute the query, we will get Sam, Sara, Michael and Null (because both the rows are null), Female, Aiden Pearce.
So, in this article we saw how to replace null values in a column.
I hope you like it. Thank you.