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”
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:
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! 🙂