Select a field and if it's null, select another with MySQL?


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

mysql> create table DemoTable1470
   -> (
   -> FirstName varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1470 values('Robert',23);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1470 values('Bob',NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1470 values(NULL,25);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1470;

This will produce the following output −

+-----------+------+
| FirstName | Age  |
+-----------+------+
| Robert    |   23 |
| Bob       | NULL |
| NULL      |   25 |
+-----------+------+
3 rows in set (0.00 sec)

Following is the query to select a field and if it's null, select another −

mysql> select coalesce(FirstName,Age) as FirstNameOrAgeValue from DemoTable1470;

This will produce the following output −

+---------------------+
| FirstNameOrAgeValue |
+---------------------+
| Robert              |
| Bob                 |
| 25                  |
+---------------------+
3 rows in set (0.00 sec)

Updated on: 10-Dec-2019

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements