MySQL SELECT from a subquery and then perform DELETE?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1947
   (
   Id int,
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1947 values(101,'Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1947 values(102,'David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1947 values(103,'Mike');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1947 values(104,'Bob');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1947 values(105,'Sam');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1947;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
|  101 | Chris |
|  102 | David |
|  103 | Mike  |
|  104 | Bob   |
|  105 | Sam   |
+------+-------+
5 rows in set (0.00 sec)

Here is the query to implement select * from subquery and then perform DELETE −

mysql> delete from DemoTable1947 where Id
   IN(select * from (select Id from DemoTable1947 order by Id limit 3)as t);
Query OK, 3 rows affected (0.00 sec)

Let us check the table records once again −

mysql> select * from DemoTable1947;

This will produce the following output −

+------+------+
| Id   | Name |
+------+------+
|  104 | Bob  |
|  105 | Sam  |
+------+------+
2 rows in set (0.00 sec)
raja
Published on 31-Dec-2019 06:38:26
Advertisements