Miscellaneous : Coalesce

November 2, 2010 by C#   PHP   SQL  

The basic purpose of a coalesce function/operator is to return the first non null value in a list of values.

In SQL 2005/2008 a coalesce looks something like this:

DECLARE @a INT,
		@b INT,
		@c INT
		
SET @a = NULL
SET @b = 2
SET @c = NULL

SELECT COALESCE(@a, @b, @c)

Read more

In C# 2.0 Microsoft added nullable types to its codebase, which included what they call the null-coalescing operator, observe:

int? a = null;
int? b = 2;
int? c = null;

Console.WriteLine(a ?? b ?? c);

Basically if you need to make a value type nullable, simply add a question mark next to the type e.g. int?

The double question mark you see in the Console.WriteLine is the null-coalescing operator.

Read more
Read even more


In PHP 5.3, developer(s) added the short ternary operator as seen below, which can be used as a coalesce style operator.

$a = null;
$b = 2;
$c = null;

echo $a ?: $b ?: $c;

Obviously if you're not going to use any of the other new functionality added to PHP 5.3, there is no point in using this operator - since it will be treated as a syntax error in versions lower than 5.3 (breaking changes).

It might be prudent to treat 5.3 as a major version, but then again 5.3.3 introduced some breaking changes as well.

Read more
Read a bit more
Read some more

Update: 2016-05-18

A proper coalesce operator (??) was added in PHP 7.x.

$a = null;
$b = 2;
$c = null;

echo $a ?? $b ?? $c;
Read more


Leave a Comment