Return value from a row if it is NOT NULL, else return the other row value in another column with MySQL

MySQLMySQLi Database

For this, you can use IFNULL(). Let us first create a table −

mysql> create table DemoTable
(
   FirstName varchar(100),
   LastName varchar(100)
);
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values(NULL,'Taylor');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('David',NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(NULL,'Miller');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| John      | Doe      |
| NULL      | Taylor   |
| David     | NULL     |
| NULL      | Miller   |
+-----------+----------+
4 rows in set (0.00 sec)

Following is the query to return value from a row if it is NOT NULL, else return the other row value in another column −

mysql> select ifnull(FirstName,LastName) as Result from DemoTable;

This will produce the following output −

+--------+
| Result |
+--------+
| John   |
| Taylor |
| David  |
| Miller |
+--------+
4 rows in set (0.00 sec)
raja
Published on 30-Sep-2019 10:19:27
Advertisements