Delete multiple entries from a MySQL table

MySQLMySQLi Database

To delete multiple entries from a MySQL table, use JOIN. Let us first create a table −

mysql> create table DemoTabl(Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100));
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(FirstName) values('Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable(FirstName) values('Adam');
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable(FirstName) values('Bob');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Adam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | Chris      |
| 2 | Bob        |
| 3 | Mike       |
| 4 | Adam       |
| 5 | Bob        |
| 6 | Adam       |
| 7 | Bob        |
| 8 | Mike       |
+----+-----------+
8 rows in set (0.00 sec)

Following is the query to delete multiple entries −

mysql> delete DemoTable
   from DemoTable
      join DemoTable tbl on DemoTable.FirstName= tbl.FirstName
      where tbl.FirstName = 'Bob';
Query OK, 3 rows affected (0.15 sec)

Let us check table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | Chris      |
| 3 | Mike       |
| 4 | Adam       |
| 6 | Adam       |
| 8 | Mike       |
+----+-----------+
5 rows in set (0.00 sec)
raja
Published on 22-Aug-2019 11:22:05
Advertisements