Null coalescing operator in C#, PHP, Bash and SQL

TIL about the null coalescing operator in C#, PHP, Bash and SQL. In general, the null coalescing operator returns the result of its first operand—if it exists and is not null.

C#:

string siteName = suppliedName ?? "Default Name";

/* is logically equivalent to */

string siteName = suppliedName != null ? suppliedName : "Default Name";

PHP:

Since PHP 7:

$siteName = $suppliedName ?? 'Default Name';

/* is logically equivalent to */

$siteName = isset($suppliedName) ? $suppliedName : 'Default Name';

Bash:

NAME=${supplied_name:-'Default Name'}
echo $NAME

Note that ${var:=val} assigns the value to the variable.

SQL:

In Oracle, SQL Server, PostgreSQL and in MySQL you can use COALASCE:

COALESCE(possibly_null_value[, possibly_null_value, ...]);

COALASCE returns the first argument that is not null. In case all terms are null, it returns null.


SHARE THIS ARTICLE