Return records that do not have a value in a certain field with two SELECT statement in a single MySQL query


For this, you can use WHERE clause along with subquery. Let us first create a table −

mysql> create table DemoTable1840
     (
     UserName varchar(20),
     UserType ENUM('GUEST','ADMIN')
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1840 values('Chris','Admin');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1840 values('David','Guest');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1840 values('Chris','Guest');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1840;

This will produce the following output −

+----------+----------+
| UserName | UserType |
+----------+----------+
| Chris    |    ADMIN |
| David    |    GUEST |
| Chris    |    GUEST |
+----------+----------+
3 rows in set (0.00 sec)

Here is the query to records that do not have a value in a certain field:

mysql> select UserName from DemoTable1840 where UserName NOT IN(select UserName from DemoTable1840 where UserType='Admin');

This will produce the following output −

+----------+
| UserName |
+----------+
| David    |
+----------+
1 row in set (0.00 sec)

Updated on: 26-Dec-2019

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements