SQL COALESCE Function



  SQL > Advanced SQL > Coalesce Function

The COALESCE function in SQL returns the first non-NULL expression among its arguments.

It is the same as the following CASE statement:

SELECT CASE ("column_name")
  WHEN "expression 1 is not NULL" THEN "expression 1"
  WHEN "expression 2 is not NULL" THEN "expression 2"
  ...
  [ELSE "NULL"]
  END
FROM "table_name"

For examples, say we have the following table,

Table Contact_Info
NameBusiness_PhoneCell_PhoneHome_Phone
Jeff531-2531622-7813565-9901
LauraNULL772-5588312-4088
PeterNULLNULL594-7477

and we want to find out the best way to contact each person according to the following rules:

1. If a person has a business phone, use the business phone number.

2. If a person does not have a business phone and has a cell phone, use the cell phone number.

3. If a person does not have a business phone, does not have a cell phone, and has a home phone, use the home phone number.

We can use the COALESCE function to achieve our goal:

SELECT Name, COALESCE(Business_Phone, Cell_Phone, Home_Phone) Contact_Phone
FROM Contact_Info;

Result:

NameContact_Phone
Jeff531-2531
Laura772-5588
Peter594-7477

Next: SQL NULLIF




Copyright © 2013 1keydata.com   All Rights Reserved.     Privacy Policy


SQL UNION
SQL UNION ALL
SQL Inline View
SQL INTERSECT
SQL MINUS
SQL LIMIT
SQL TOP
SQL Subquery
SQL EXISTS
SQL CASE
SQL DECODE
SQL AUTO INCREMENT
SQL IDENTITY
SQL SEQUENCE And NEXTVAL
SQL NULL
SQL ISNULL
SQL IFNULL
SQL NVL
SQL COALESCE
SQL NULLIF
SQL Rank
SQL Median
SQL Running Totals
SQL Percent to Total
SQL Cumulative Percent to Total


SQL Video Tutorial
SQL Jobs




Site Map
Resources