ISNULL() Function, COALESCE() Function And CASE Statement

Introduction

There are three ways in which we can remove Null values in Table data and show them to the user.

Description

In our Table data, some columns contain null values. We can replace it using ISNULL() function , COALESCE() function, and CASE Statement.

Steps

Create one table.
  1. CREATE TABLE [dbo].[tblEmployees](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [Gender] [nvarchar](10) NULL,  
  5.     [Salary] [intNULL,  
  6. PRIMARY KEY CLUSTERED   
  7. (  
  8.     [Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]  
  11. GO 
Then, enter some dummy records.

 
Replace the Null value using ISNULL() function.
  1. SELECT E.Name as Employee, ISNULL(M.Gender,'No Gender'as Gender  
  2. FROM tblEmployees E  
  3. LEFT JOIN tblEmployees M  
  4. ON E.Id = M.Id 


Replace the Null value using COALESCE() function() function.
  1. SELECT E.Name as Employee, COALESCE(M.Gender,'No Gender'as Gender  
  2. FROM tblEmployees E  
  3. LEFT JOIN tblEmployees M  
  4. ON E.Id = M.Id 


Replace the Null value using CASE statement.
  1. SELECT E.Name as Employee, CASE WHEN M.Gender IS NULL THEN 'No Gender'   
  2.    ELSE M.Gender END as Gender  
  3. FROM  tblEmployees E  
  4. LEFT JOIN tblEmployees M  
  5. ON E.Id = M.Id 
 
Summary

Here, we learned the following -
  1. ISNULL() function , COALESCE() function and CASE Statement.
  2. Why and how we use these.