Syntax error MySQL query to replace null value with empty string in several columns while fetching data

MySQL query to replace null value with empty string in several columns while fetching data



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

mysql> create table DemoTable1849
     (
     ClientFirstName varchar(20),
     ClientLastName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1849 values('John',NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1849 values(NULL,'Miller');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1849 values(NULL,NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1849 values('Chris','Brown');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1849;

This will produce the following output −

+-----------------+----------------+
| ClientFirstName | ClientLastName |
+-----------------+----------------+
| John            |           NULL |
| NULL            |         Miller |
| NULL            |           NULL |
| Chris           |          Brown |
+-----------------+----------------+
4 rows in set (0.00 sec)

Here is the query to replace null value with empty string in several columns while fetching data −

mysql> select ifnull(ClientFirstName,'') as ClientFirstName,ifnull(ClientLastName,'') as ClientLastName from DemoTable1849;

This will produce the following output −

+-----------------+----------------+
| ClientFirstName | ClientLastName |
+-----------------+----------------+
| John            |                |
|                 |         Miller |
|                 |                |
| Chris           |          Brown |
+-----------------+----------------+
4 rows in set (0.00 sec)
Updated on: 2019-12-26T06:26:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements