Display 1 for NULL values in MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1963
   (
   Counter int
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1963 values(20);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1963 values(NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1963 values(99);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1963 values(49);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1963 values(NULL);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1963;

This will produce the following output −

+---------+
| Counter |
+---------+
|      20 |
|    NULL |
|      99 |
|      49 |
|    NULL |
+---------+
5 rows in set (0.00 sec)

Here is the query to display 1 for NULL values in MySQL:

mysql> update DemoTable1963 set Counter=IFNULL(Counter,0)+1 where Counter IS NULL;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1963;

This will produce the following output −

+---------+
| Counter |
+---------+
|      20 |
|       1 |
|      99 |
|      49 |
|       1 |
+---------+
5 rows in set (0.00 sec)
raja
Published on 31-Dec-2019 07:26:56
Advertisements