Write a single MySQL query to return the ID from the corresponding row which is a NOT NULL value

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   StudentId int,
   StudentName varchar(100)
);
Query OK, 0 rows affected (0.85 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(NULL,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(NULL,'Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(101,'David');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(102,'Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(103,'Sam');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|      NULL | Chris       |
|      NULL | Robert      |
|       101 | David       |
|       102 | Mike        |
|       103 | Sam         |
+-----------+-------------+
5 rows in set (0.00 sec)

Following is the query to return ID from the corresponding row which is a NOT NULL value −

mysql> select StudentId from DemoTable where StudentName='David' and StudentId IS NOT NULL;

This will produce the following output −

+-----------+
| StudentId |
+-----------+
|       101 |
+-----------+
1 row in set (0.00 sec)
raja
Published on 26-Sep-2019 07:59:36
Advertisements