Delete records from a MySQL table with IN() in a single query


Let us create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1922(StudentName) values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1922(StudentName) values('Robert');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1922(StudentName) values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1922(StudentName) values('Mike');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1922;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Robert      |
|         3 | David       |
|         4 | Mike        |
+-----------+-------------+
4 rows in set (0.00 sec)

Here is the query to delete records from a table with IN() −

mysql> delete from DemoTable1922 where StudentId IN(1,2,3,4);
Query OK, 4 rows affected (0.00 sec)

Let us check table records once again −

mysql> select * from DemoTable1922;

This will produce the following output −

Empty set (0.00 sec)

Updated on: 30-Dec-2019

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements