Click here to Skip to main content
15,846,518 members
Articles / Database Development / SQL Server
Tip/Trick

Using Coalesce() in sqlserver

Rate me:
Please Sign up or sign in to vote.
4.68/5 (23 votes)
11 Jun 2013CPOL 138.6K   8   11
SQL Server built-in functions Coalesce()

Introduction

When we have multi-value attribute with single or more null values in a Table, the Coalesce() function is very useful.

Using the Code

If you consider the below facts placed in a employee table with Id, Name, ph_no, Alt_no, Office no.

id

Name

Ph_ no

Alt_ no

Office no

101

Albert

999999

456453

321333

102

khan

null

null

123455

103

victor

112121

null

null

104

lovely

null

null

1897321

The above Employee table may have single value or three values. If it has single value, then it fills null values with remaining attributes.

When we retrieve the number from employee table, that number Should Not be Null value. To get not null value from employee table, we use Coalesce() function. It returns the first encountered Not Null Value from employee table.

SQL
select id , name ,coalesce(Ph_no,Alt_no,Office_no) as contact number from employee 

It returns:

id

Name

Contactnumber

101

Albert

999999

102

khan

123455

103

victor

112121

104

lovely

1897321

Thank you!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
iam software developer on dotnet....
now i am @ hyderabad
This is a Organisation (No members)


Comments and Discussions

 
QuestionThanks a lot ,I am very grateful to you. Pin
naren 819861414-Mar-19 21:38
naren 819861414-Mar-19 21:38 
AnswerRe: Thanks a lot ,I am very grateful to you. Pin
blnreddy23-Dec-19 1:35
professionalblnreddy23-Dec-19 1:35 
GeneralMy vote of 3 Pin
Umesh AP18-Aug-15 21:44
Umesh AP18-Aug-15 21:44 
GeneralRe: My vote of 3 Pin
blnreddy23-Dec-19 1:36
professionalblnreddy23-Dec-19 1:36 
Thumbs Up | :thumbsup:

blnreddy6@gmail.com
http://fresherstechkeys.blogspot.in/
GeneralMy vote of 5 Pin
Animesh Datta29-May-14 20:29
Animesh Datta29-May-14 20:29 
GeneralMy vote of 5 Pin
ashumeerut12-May-14 8:05
ashumeerut12-May-14 8:05 
GeneralMy vote of 5 Pin
shravanyadav18-Mar-14 4:09
shravanyadav18-Mar-14 4:09 
QuestionOne doubt Pin
♥…ЯҠ…♥23-Dec-13 18:52
professional♥…ЯҠ…♥23-Dec-13 18:52 
AnswerRe: One doubt Pin
blnreddy19-Mar-14 9:38
professionalblnreddy19-Mar-14 9:38 
GeneralRe: One doubt Pin
♥…ЯҠ…♥19-Mar-14 19:24
professional♥…ЯҠ…♥19-Mar-14 19:24 
GeneralMy vote of 5 Pin
Balasubramanian T4-Aug-13 22:47
Balasubramanian T4-Aug-13 22:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.