COALESCE statement in SQL Server

The COALESCE statement returns the expression with the first non-NULL value among the passed expressions.

This article will show you in detail how to use the COALESCE statement handling function in SQL Server with specific syntax and examples to better visualize and capture functions.

Describe

The COALESCE statement returns the expression with the first non-NULL value among the passed expressions. If all expressions are NULL then COALESCE will return NULL.

Syntax

To use the COALESCE statement in SQL Server, we use the following syntax:

 COALESCE (bieuthuc_1, bieuthuc_2,. bieuthuc_n) 

Parameters :

  1. bieuthuc_1, bieuthuc_2, . bieuthuc_n : is an expression of any type. All of these expressions must be in the same form or convert to the same form. For example, bieuthuc_1 is a string type, bieuthuc_2 to bieuthuc_n must also be a string type, similar to bieuthuc_1 is a numeric type then bieuthuc_2 to bieuthuc_n must also be numeric type .

Note :

  1. COALESCE can be used in later versions of SQL Server: SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, and SQL Server 2005.

For example

Take a look and explore some examples of COALESCE statements in SQL Server.

 SELECT COALESCE(NULL, NULL, 'TipsMake.com', NULL, 'ChuyenCongNghe'); 
Result: 'TipsMake.com'

SELECT COALESCE(NULL, 'TipsMake.com', 'Quantrimang');
Result: 'TipsMake.com'

SELECT COALESCE(NULL, NULL, 1, 2, 3, NULL, 4);
Result: 1

Previous post: CASE command in SQL Server

Next lesson: CURRENT_USER command in SQL Server

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile