How to use Coalesce in MySQL?

MySQLMySQLi Database

The coalesce in MySQL can be used to return first not null value. If there are multiple columns, and all columns have NULL value then it returns NULL otherwise it will return first not null value.

The syntax is as follows.

SELECT COALESCE(yourColumnName1,yourColumnName2,yourColumnName3,.......N) as
anyVariableName from yourTableName;

To understand the above syntax, let us first create a table. The query to create a table is as follows.

mysql> create table CoalesceDemo
-> (
-> Id int,
-> Name varchar(100),
-> Age int,
-> Address varchar(100)
-> );
Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command. The query is as follows.

mysql> insert into CoalesceDemo values(1,NULL,NULL,NULL);
Query OK, 1 row affected (0.14 sec)

mysql> insert into CoalesceDemo values(NULL,'Mike',NULL,NULL);
Query OK, 1 row affected (0.17 sec)

mysql> insert into CoalesceDemo values(NULL,NULL,23,NULL);
Query OK, 1 row affected (0.24 sec)

mysql> insert into CoalesceDemo values(NULL,NULL,NULL,'UK');
Query OK, 1 row affected (0.14 sec)

mysql> insert into CoalesceDemo values(NULL,NULL,NULL,NULL);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement. The query is as follows.

mysql> select *from CoalesceDemo;

The following is the output.

+------+------+------+---------+
| Id    | Name | Age | Address |
+------+------+------+---------+
| 1    | NULL | NULL | NULL    |
| NULL | Mike | NULL | NULL    |
| NULL | NULL | 23   | NULL    |
| NULL | NULL | NULL | UK      |
| NULL | NULL | NULL | NULL    |
+------+------+------+---------+
5 rows in set (0.00 sec)

Here are all the cases where you can return the first NOT NULL value. The query is as follows.

mysql> select Coalesce(Id,Name,Age,Address) as FirstNotNullValue from CoalesceDemo;

The following is the output.

+-------------------+
| FirstNotNullValue |
+-------------------+
| 1                 |
| Mike              |
| 23                |
| UK                |
| NULL              |
+-------------------+
5 rows in set (0.00 sec)
raja
Published on 11-Jan-2019 11:46:40
Advertisements