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



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)
Updated on: 2019-11-05T07:01:32+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements