Return only the non-empty and non-null values from a table and fill the empty and NULL values with the corresponding column values in MySQL?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable839(
   StudentFirstName varchar(100),
   StudentLastName varchar(100)
);
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable839 values('Chris','Brown');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable839 values('','Taylor');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable839 values(NULL,'Taylor');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable839 values('Adam','Smith');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable839;

This will produce the following output −

+------------------+-----------------+
| StudentFirstName | StudentLastName |
+------------------+-----------------+
| Chris            | Brown           |
|                  | Taylor          |
| NULL             | Taylor          |
| Adam             | Smith           |
+------------------+-----------------+
4 rows in set (0.00 sec)

Following is the query to return only the non-empty and non-null values from a table and fill the empty and NULL values with the corresponding column values−

mysql> select if(length(StudentFirstName),StudentFirstName,StudentLastName) from DemoTable839;

This will produce the following output −

+---------------------------------------------------------------+
| if(length(StudentFirstName),StudentFirstName,StudentLastName) |
+---------------------------------------------------------------+
| Chris                                                         |
| Taylor                                                        |
| Taylor                                                        |
| Adam                                                          |
+---------------------------------------------------------------+
4 rows in set (0.00 sec)
raja
Published on 03-Sep-2019 16:31:17
Advertisements