How can I set 0 if a query returns a null value in MySQL?

MySQLMySQLi Database

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

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Value int
   -> );
Query OK, 0 rows affected (0.71 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value) values(100);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Value) values(140);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Value) values(200);
Query OK, 1 row affected (0.26 sec)

mysql> insert into DemoTable(Value) values(450);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Value) values(null);
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Value) values(90);
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Value) values(null);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+-------+
| Id | Value |
+----+-------+
| 1  | 100   |
| 2  | 140   |
| 3  | 200   |
| 4  | 450   |
| 5  | NULL  |
| 6  | 90    |
| 7  | NULL  |
+----+-------+
7 rows in set (0.00 sec)

Following is the query to set 0 if a query returns a null value in MySQL.

mysql> select ifnull(Value,0) AS Value from DemoTable;

Output

+-------+
| Value |
+-------+
| 100   |
| 140   |
| 200   |
| 450   |
| 0     |
| 90    |
| 0     |
+-------+
7 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 12:17:19
Advertisements