Site icon TestingDocs.com

MySQL EXISTS Operator

Overview

In this tutorial, we will learn about MySQL EXISTS Operator. The EXISTS operator checks whether a subquery returns any rows. If the subquery returns rows the EXISTS operator returns true to the outer query.

The NOT EXISTS operator is the opposite of the EXISTS. If the subquery returns any rows the NOT EXISTS returns false.

Example

In this example, we will use the Country and the City table from the world MySQL database. The following example is checking for cities whose population is greater than 10 million using a subquery, and then returning a list of continents where those cities exists in the outer query.

EXISTS Operator

mysql> SELECT Continent FROM Country WHERE
-> EXISTS (SELECT * FROM City WHERE Code =
-> Countrycode AND Population > 10000000)
-> GROUP BY Continent;

+———–+
| Continent |
+———–+
| Asia |
+———–+
1 row in set (0.00 sec)

NOT EXISTS

Let’s change the operator to NOT EXISTS and check the results of the query. Notice in the results below additional continents are displayed. Therefore, all of these continents contains cities that do not have population greater than 10 million.

mysql> SELECT Continent FROM Country WHERE
-> NOT EXISTS (SELECT * FROM City WHERE Code =
-> Countrycode AND Population > 10000000)
-> GROUP BY Continent;
+—————+
| Continent |
+—————+
| North America |
| Asia |
| Africa |
| Europe |
| South America |
| Oceania |
| Antarctica |
+—————+

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/

For more information on MySQL Database:

https://www.mysql.com/

Exit mobile version