Set the NULL values to 0 and display the entire column in a new column with MySQL SELECT

MySQLMySQLi Database

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

mysql> create table DemoTable (Value int);
Query OK, 0 rows affected (1.02 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
| NULL  |
| 10    |
| 20    |
| NULL  |
| 30    |
+-------+
5 rows in set (0.00 sec)

Set NULL values to 0 −

mysql> select Value,IFNULL(Value,0) from DemoTable;

This will produce the following output −

+-------+-----------------+
| Value | IFNULL(Value,0) |
+-------+-----------------+
| NULL  | 0               |
| 10    | 10              |
| 20    | 20              |
| NULL  | 0               |
| 30    | 30              |
+-------+-----------------+
5 rows in set (0.00 sec)
raja
Published on 22-Aug-2019 10:14:54
Advertisements