Select from table where value does not exist with MySQL?

MySQLMySQLi Database

For this, you can use NOT IN() −

mysql> create table DemoTable1991
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20)
);
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1991(StudentName) values('Chris');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1991(StudentName) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1991(StudentName) values('David');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1991(StudentName) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1991(StudentName) values('Mike');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1991;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Bob         |
|         3 | David       |
|         4 | Sam         |
|         5 | Mike        |
+-----------+-------------+
5 rows in set (0.03 sec)

Here is the query to select * from table where value does not exist:

mysql> select * from DemoTable1991
   where StudentName NOT IN('Bob','Sam','Mike');

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         3 | David       |
+-----------+-------------+
2 rows in set (0.04 sec)
raja
Published on 02-Jan-2020 05:20:22
Advertisements