Delete rows in a table using Subquery
Delete rows in a table using Subquery
In this tutorial, we will learn how to delete rows using a subquery. Subqueries are not limited to SELECT statements. We can use them to update or delete rows in a table.
Syntax
The general syntax for the SQL statement is as follows:
DELETE FROM <table_name>
WHERE <condition>
(<Sub query>)
Example
In this example, we will use the City table from the world MySQL table. We will remove all the cities from the City table that has population less than 100.
Let’s check how many Cities have population < 100 in the City table with the following query.
mysql> SELECT * FROM City WHERE Population < 100;
+——+———–+————-+————+
| ID | Name | CountryCode | Population |
+——+———–+————-+————+
| 2912 | Adamstown | PCN | 42 |
+——+———–+————-+————+
1 row in set (0.00 sec)
Let’s delete the city from the City table using subquery
mysql> DELETE FROM City
-> WHERE CountryCode IN
-> (SELECT c.CountryCode
-> FROM (SELECT * FROM City ) AS c
-> WHERE c.Population < 100 );
Query OK, 1 row affected (0.04 sec)
—
MySQL Tutorials
MySQL Tutorials on this website:
https://www.testingdocs.com/mysql-tutorials-for-beginners/
For more information on MySQL Database: