SQL Day 15: Replacing NULL in SQL
LO1: Replacing NULL with ISNULL function
LO2: Replacing NULL with COALESCE function
LO3: Replacing NULL with Case Statement
Prerequisite: Self Joins
In the previous session, we have found the employee’s managers using the Left Outer Join and we get the NULL value for the employee who does not have the manager assign or we can say he is the BOSS!
So now we are trying to replace this NULL value with the specified text using different methods.
Replacing NULL with ISNULL function
The ISNULL function accepts two parameters. First is the expression and second are the replacement value i.e. the value which is replaced by NULL.
If the expression you have passed in ISNULL function returns the NULL then NULL will be replaced by the given value as per the second parameter.
Now applying the ISNULL function in the Left Join to replace the NULL value with the text saying “BOSS”.
select e.Name as Employee, ISNULL(m.Name,'BOSS') as Manager
from tblemployee e
Left Join tblemployee m
ON e.ManagerID=m.ID
As you can see in the screen above, the NULL value us replaced by the text “BOSS”.
Replacing NULL with COALESCE function
The COALESCE function is similar to the ISNULL function but the COALESCE function is more powerful than the ISNULL function. In COALESCE we can pass the multiple expression which will be covered in next session in greater details.
To use the COALESCE function we need to replace the ISNULL with COALESCE in the query and we will get the same result.
select e.Name as Employee, COALESCE(m.Name,'BOSS') as Manager
from tblemployee e
Left Join tblemployee m
ON e.ManagerID=m.ID
Note: We will talk about the COALESCE function in next session.
Replacing NULL with Case Statement
The Case statement is also easy to use. Below is the syntax of Case Statement.
Syntax: Case When ‘Expression’ Then ‘Value1’ Else ‘Value2’ End
If the expression returns the true then the value1 will be used else value2 is used when expression returns false.
Let’s use the Case Statement to replace the NULL value.
select e.Name as Employee,
CASE
WHEN m.Name IS NULL THEN 'BOSS' ELSE m.Name
END
as Manager
from tblemployee e
Left Join tblemployee m
ON e.ManagerID=m.ID
That’s all for today. Thank You.
Comments
Post a Comment