How to set default value for empty row in MySQL?


To set default value for empty row, use the concept of COALESCE(). Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1863 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1863 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1863 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1863 values(NULL);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1863;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| Chris     |
| NULL      |
| David     |
| NULL      |
+-----------+
4 rows in set (0.00 sec)

Following is the query to set default value for empty row −

mysql> select coalesce(FirstName,'UNKNOWN NAME') from DemoTable1863;

This will produce the following output −

+------------------------------------+
| coalesce(FirstName,'UNKNOWN NAME') |
+------------------------------------+
| Chris                              |
| UNKNOWN NAME                       |
| David                              |
| UNKNOWN NAME                       |
+------------------------------------+
4 rows in set (0.00 sec)

Updated on: 26-Dec-2019

516 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements