What you want to see on DotNetFunda.com ?
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 16330 |  Welcome, Guest!   Register  Login
 Home > Interview Questions > SQL Server Interview Questions > What is the use of COALESCE in SQL Serve ...

What is the use of COALESCE in SQL Server?

Interview question and answer by: Raja | Posted on: 12/14/2008 | Category: SQL Server Interview questions | Views: 26164 |


Answer:

Coalesce returns the first non-null expression among its arguments.

Lets say we have to return a non-null from more than one column, then we can use COALESCE function.

SELECT COALESCE(hourly_wage, salary, commission) AS 'Total Salary' FROM wages


In this case,

If hourly_wage is not null and other two columns are null then hourly_wage will be returned.
If hourly_wage, commission are null and salary is not null then salary will be returned.
If commission is non-null and other two columns are null then commission will be returned.

Asked In: Many Interviews | Alert Moderator 
Found interesting? Add this to:


 Responses

Posted by: Jayanti | Posted on: 22 Dec 2011 06:45:48 AM | Points: 10 | Alert Moderator 

If all 3 attributes are null then?

Posted by: Manaskumarm | Posted on: 17 Sep 2012 08:19:36 AM | Points: 10 | Alert Moderator 

"If all 3 attributes are null then?"
Then it will return as NULL . We can handle following way.

#1. So we need to handle in our server side code.

#2. SELECT ISNULL((CAST(COALESCE(hourly_wage, salary, commission) AS money)),0) AS 'Total Salary'
FROM wages;
It will return 0.00

Posted by: Me_Himanshu | Posted on: 06 Mar 2013 01:56:33 PM | Points: 10 | Alert Moderator 

coalesce function is used to replace the first not null value from an expression
check the below example-
if we have a table having name,mobileno,landline as columns
name mobileno landline
abc 9892133 null
def null 0223111
ghi null 0112233
jkl 998822 null
mno 998299 04488822
pqr null null
then the result of follwing query
select name,coalesce(mobileno,landline) as contact from tablename
would return the result
name contact
abc 9892133
def 0223111
ghi 0112233
jkl 998822
mno 998299 (first not null value)
pqr

>> Write Response - Respond to this post and get points

Even more ... | Submit Interview Questions and win prizes!

More Interview Questions from Raja

Even more ... | Submit Interview Questions and win prizes!


About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/25/2013 3:06:17 PM