Select different fields in MySQL even if a field is set to null?

MySQLMySQLi Database

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

mysql> create table DemoTable1336
   -> (
   -> FirstName varchar(20)
   -> ,
   -> SecondName varchar(20)
   -> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1336 values('John',NULL);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1336 values(NULL,'Chris');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1336 values('David','Mike');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1336;

This will produce the following output −

+-----------+------------+
| FirstName | SecondName |
+-----------+------------+
| John      | NULL       |
| NULL      | Chris      |
| David     | Mike       |
+-----------+------------+
3 rows in set (0.00 sec)

Following is the query to select different fields in MySQL even if a field is set to null −

mysql> select coalesce(FirstName,SecondName) as AlternateName from DemoTable1336;

This will produce the following output −

+---------------+
| AlternateName |
+---------------+
| John          |
| Chris         |
| David         |
+---------------+
3 rows in set (0.00 sec)
raja
Published on 05-Nov-2019 11:31:32
Advertisements