Using SQL COALESCE to Find the First Non-NULL Value

You are looking to find a way to find the first non-null value from a list of fields. In this post, we look at SQL COALESCE  a wonderfully useful tool that helps to solve that problem.

To help demonstrate this, we will talk about a hypothetical scenario where a number of customer leads have been added to a table from different sources and the consistency of data found in some of the key fields is sparse.

Here is the data, the table is called “Leads”

SQL COALESCE example

For the purposes of this example, the task is to pull out a single column list of phone numbers for the leads in the table and that involves finding the first non-null value.

Here is what you do:

SELECT 
  COALESCE(HomePhone, BusinessPhone, MobilePhone) AS Phone 
FROM Leads;

This produces a list:

SQL COALESCE result

You can see that it has taken the first phone number (non-null value) found based on the order of columns passed into COALESCE.

It is possible to write this in another way using SELECT CASE

SELECT 
 CASE WHEN HomePhone IS NOT NULL THEN HomePhone
      WHEN BusinessPhone IS NOT NULL THEN BusinessPhone
      WHEN MobilePhone IS NOT NULL THEN MobilePhone
   END AS Phone
FROM Leads;

The result is the same but it takes longer to write the code so using COALESCE in your SQL statement is certainly more efficient in this case – less is more! 🙂

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestBuffer this pageShare on RedditShare on StumbleUpon
About Andy Hayes

Andy Hayes is a DBA working with SQL Server since version 7.0. He has a wonderful wife and two beautiful children. He loves database technology, playing cricket, and blogging. He is passionate about sharing his experiences as a DBA and learning more to further his understanding and knowledge. You can follow me on Twitter, check out my Facebook page or follow me on

Speak Your Mind

*

*