Introduction to COALESCE
COALESCE is nothing but a version of ISNULL, that can take more than two parameters. COALESCE is also part of ANSI-92. Basically, it returns the first non-null expression from its arguments. If all arguments that are passed to COALESCE are null then COALESCE will return null.
SELECT COALESCE('A','B')
--This Returns 'A'
SELECT COALESCE(NULL,'B')
--This Returns 'B'
SELECT COALESCE(NULL,'B' , 'C', null,'D')
--This Returns 'B'
SELECT COALESCE(NULL,NULL,NULL,'C')
--This Returns 'C'
Practical use of COALESCE
For example, we have a table called Employees and the definition of this table is as in the following and it has some dummy data.
CREATE TABLE #Employees
(
EmployeeId INT,
EmployeeName VARCHAR(50),
PhoneNumber VARCHAR(12),
MobileNumber VARCHAR(12),
WorkPhoneNumber VARCHAR(12)
)
INSERT INTO #Employees VALUES(1,'Jignesh','3890001123','3890001124','(389)0001123')
INSERT INTO #Employees VALUES(1,'Tejas',NULL,'4590001124','(389)0001124')
INSERT INTO #Employees VALUES(1,'Rakesh',NULL,NULL,'(278)0001123')
INSERT INTO #Employees VALUES(1,'Punit',NULL,NULL,NULL)

Here the employee has three contact details, Phone Number (main contact), Mobile Number, and Work Phone Number. Now as per my requirement, I must show the employee detail with the main contact detail (phone Number), if the main contact detail is null then I must show the secondary contact detail (Mobile Number), if the secondary contact detail is null then I must show the third contact detail (work Phone Number) and if all contacts are null then show the value null.
EmployeeId EmployeeName ContactDetail
-
Jignesh 3890001123
-
Tejas 4590001124
-
Rakesh (278)0001123
-
Punit NULL
So I initially thought to write the following type of query:
SELECT EmployeeId,EmployeeName,
CASE WHEN (PhoneNumber IS NULL) THEN
(CASE WHEN (MobileNumber IS NULL) THEN WorkPhoneNumber
ELSE MobileNumber END)
ELSE PhoneNumber
END AS ContactDetail1
FROM #Employees
The same query result can be done using COALESCE.
SELECT EmployeeId,EmployeeName,
COALESCE(PhoneNumber,MobileNumber,WorkPhoneNumber) AS ContactDetail
FROM #Employees
Vijay Pratap SinghPosted Feb 8, 2023, 9:50 AM
Helpful! Good Article Sir
Shakti SaxenaPosted Aug 16, 2015, 1:23 PM
Very Good Article
Shiv kumarPosted Aug 9, 2013, 7:32 AM
Thanks Jignesh great explanation
Keyur PatelPosted Apr 16, 2013, 5:53 AM
Thanks Jignesh, Very nice explanation in detail about the ISNULL VS COALESCE
Gaurav GuptaPosted Apr 9, 2013, 11:00 PM
Very Well Explanation...