How does COALESCE order results with NULL and NON-NULL values?

MySQLMySQLi Database

The COALESCE() finds the NON-NULL value first If it finds the same in the beginning, then it returns, otherwise moves ahead to check NON-NULL value.

Let us first create a table −

mysql> create table DemoTable
(
   Number1 int,
   Number2 int
);
Query OK, 0 rows affected (5.48 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,200);
Query OK, 1 row affected (0.40 sec)
mysql> insert into DemoTable values(NULL,50);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(10,NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(NULL,NULL);
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------+---------+
| Number1 | Number2 |
+---------+---------+
|     100 | 200     |
|    NULL | 50      |
|      10 | NULL    |
|    NULL | NULL    |
+---------+---------+
4 rows in set (0.00 sec)

Following is the query to order records with COALESCE −

mysql> select coalesce(Number1,Number2) AS NON_NULL_ARGUMENT_FIRST from DemoTable;

This will produce the following output −

+-------------------------+
| NON_NULL_ARGUMENT_FIRST |
+-------------------------+
| 100                     |
| 50                      |
| 10                      |
| NULL                    |
+-------------------------+
4 rows in set (0.00 sec)
raja
Published on 04-Oct-2019 08:29:30
Advertisements