Fetching records from a table with NULL and other values on the basis of conditions in MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   value1 int,
   value2 int,
   value3 int
);
Query OK, 0 rows affected (0.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(20,40,null);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(40,40,null);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(null,null,null);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+--------+--------+
| value1 | value2 | value3 |
+--------+--------+--------+
|     20 |     40 | NULL   |
|     40 |     40 | NULL   |
|   NULL |   NULL | NULL   |
+--------+--------+--------+
3 rows in set (0.00 sec

Here is the query to fetch records on the basis of NULL and other values on the basis of some condition −

mysql> select *from DemoTable
where (value1 is null or value1!=20) and
(value2 is null or value2!=20) and
(value3 is null or value3!=20);

This will produce the following output −

+--------+--------+--------+
| value1 | value2 | value3 |
+--------+--------+--------+
|     40 |     40 | NULL   |
|   NULL |   NULL | NULL   |
+--------+--------+--------+
2 rows in set (0.00 sec)
raja
Published on 30-Sep-2019 07:10:17
Advertisements