Return 0 in a new column when record is NULL in MySQL?

MySQLMySQLi Database

For this, you can use CASE statement. Let us first create a table −

mysql> create table DemoTable703 (Price int);
Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable703 values(102);
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable703 values(null);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable703 values(0);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable703 values(500);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable703 values(100);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable703 values(null);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable703 values(2340);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable703;

This will produce the following output -

+-------+
| Price |
+-------+
| 102   |
| NULL  |
| 0     |
| 500   |
| 100   |
| NULL  |
| 2340  |
+-------+
7 rows in set (0.00 sec)

Use CASE statement −

mysql> select Price, case When Price IS NULL Then 0 else Price END AS Result from DemoTable703;

This will produce the following output -

+-------+--------+
| Price | Result |
+-------+--------+
| 102   | 102    |
| NULL  | 0      |
| 0     | 0      |
| 500   | 500    |
| 100   | 100    |
| NULL  | 0      |
| 2340  | 2340   |
+-------+--------+
7 rows in set (0.00 sec)
raja
Published on 21-Aug-2019 12:03:03
Advertisements