MySQL CASE statement to place custom values in place of NULL


Let us first create a table −

mysql> create table DemoTable
(
   FirstName varchar(20)
);
Query OK, 0 rows affected (1.15 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| John      |
| NULL      |
| Adam      |
| NULL      |
+-----------+
4 rows in set (0.00 sec)

Let us now use CASE statement −

mysql> select case when FirstName is NULL then 'UNKNOWN NAME' else FirstName end AS FirstName from DemoTable;

This will produce the following output −

+--------------+
| FirstName    |
+--------------+
| John         |
| UNKNOWN NAME |
| Adam         |
| UNKNOWN NAME |
+--------------+
4 rows in set (0.00 sec)

We can also get the same results using IFNULL() −

mysql> select IFNULL(FirstName,'UNKNOWN NAME') AS FirstName from DemoTable;

This will produce the following output −

+--------------+
| FirstName    |
+--------------+
| John         |
| UNKNOWN NAME |
| Adam         |
| UNKNOWN NAME |
+--------------+
4 rows in set (0.00 sec)

Updated on: 07-Oct-2019

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements