Apart from using COALESCE(), there are 2 other ways to replace NULL values in SQL Server. Let's understand this with an example.
I have a Table tblEmployee, as shown in the diagram below. Some of the Employees does not have gender. All those employees who does not have Gender, must have a replacement value of 'No Gender' in your query result. Let's explore all the 3 possible options we have.
Option 1 : Replace NULL values in SQL Server using ISNULL() function.
Select Name, ISNULL(Gender,'No Gender') as Gender
From tblEmployee
Option 2 : Replace NULL values in SQL Server using CASE.
Select Name, Case When Gender IS NULL Then 'No Gender' Else Gender End as Gender
From tblEmployee
Option 3 : Replace NULL values in SQL Server using COALESCE() function.
Select Name, Coalesce(Gender, 'No Gender') as Gender
From tblEmployee
These are the 3 options that I can think of at the moment. If you can think of any other option, please post it here.
Using the ISNULL function ie
ReplyDeleteSelect Name, ISNULL(Gender,'No Gender') as Gender
From tblEmployee
only the first letter is updated ie it has to display as "No Gender" but displaying as N
Please check your 'Gender' column data type. make sure your column length is greater than or equal to 9.
Deleteselect iif(gender is null,'no gender',gender) from sample
Deletewhat is the difference between coalesce and isnull?
ReplyDeleteCoalesce is use for more than two columns where as Isnull works only for two column. Also you can use coalesce function in joining to get first not null value from more than two different table.
Deletethe major difference is coalesce replaces the null value with the first not null value among the arguments whereas isnull replaces the null value with specified replacement value
DeleteSome how iif() and nullif also try to do something
ReplyDeletewhat is parameter sniffing ?
ReplyDelete