How to find records with a null value in a set of columns with MySQL


For this, use the concept of GREATEST(). Let us first create a table −

mysql> create table DemoTable1862
     (
     Value1 int,
     Value2 int,
     Value3 int,
     Value4 int
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1862 values(43,34,56,42);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1862 values(NULL,78,65,NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1862 values(110,NULL,78,NULL);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1862;

This will produce the following output −

+--------+--------+--------+--------+
| Value1 | Value2 | Value3 | Value4 |
+--------+--------+--------+--------+
|     43 |     34 |     56 |     42 |
|   NULL |     78 |     65 |   NULL |
|    110 |   NULL |     78 |   NULL |
+--------+--------+--------+--------+
3 rows in set (0.00 sec)

Here is the query to find records with a null value in a set of columns −

mysql> select * from DemoTable1862 where greatest(Value1,Value2,Value3,Value4) IS NULL;

This will produce the following output −

+--------+--------+--------+--------+
| Value1 | Value2 | Value3 | Value4 |
+--------+--------+--------+--------+
|   NULL |     78 |     65 |   NULL |
|    110 |   NULL |     78 |   NULL |
+--------+--------+--------+--------+
2 rows in set (0.00 sec)

Updated on: 26-Dec-2019

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements