MySQL query to compare and display only the rows with NULL values

MySQLMySQLi Database

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

mysql> create table DemoTable
(
   Value1 int,
   Value2 int
);
Query OK, 0 rows affected (0.75 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10,NULL);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(20,40);
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable values(3,NULL);
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 | NULL   |
|     20 | 40     |
|     3 | NULL    |
+--------+--------+
3 rows in set (0.00 sec)

Following is the query to display the rows with NULL values −

mysql> select *from DemoTable where Value1 > IFNULL(Value2,0);

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 | NULL   |
|      3 | NULL   |
+--------+--------+
2 rows in set (0.00 sec)
raja
Published on 30-Sep-2019 06:47:12
Advertisements