Database

MySQL Correlated Subquery

MySQL Correlated Subquery

In this tutorial, you will learn about correlated subqueries with an example. MySQL correlated subquery contains subquery references in the outer query and cannot be evaluated independently.

Example

In this example, we will use the City and the Country tables from the world MySQL database. The table structures and the column names are as follows:

mysql> DESC City;
+————-+———-+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+————-+———-+——+—–+———+—————-+
| ID | int | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | |
| CountryCode | char(3) | NO | MUL | | |
| District | char(20) | NO | | | |
| Population | int | NO | | 0 | |
+————-+———-+——+—–+———+—————-+

 

City Table Structure World Database

 

mysql> DESC Country \G

 

DESCRIBE Country World Table

Correlated Subquery

Let’s count the number of cites for each country using a correlated subquery. This query uses a correlated subquery to count the number of cities in the City table which have a matching country code to those in the Country table. The outer query then selects the country names, continents and their respective city counts.

mysql> SELECT Name,Continent,
             (SELECT COUNT(*) FROM City
             WHERE CountryCode=Country.Code)
              AS City_Count FROM Country;

The subquery reference to the Country table from the outer query makes it a correlated subquery. Due to this reference, this subquery cannot be executed as a stand-along query.

To show the output let’s filter the query to display a single country result. For example, to display the number of cities of the Canada country, we can use the following query:

mysql> SELECT Name,Continent,
-> (SELECT COUNT(*) FROM City
-> WHERE CountryCode=Country.Code)
-> AS City_Count FROM Country
-> WHERE Name =’Canada’;
+——–+—————+————+
| Name | Continent | City_Count |
+——–+—————+————+
| Canada | North America | 49 |
+——–+—————+————+
1 row in set (0.00 sec)

 

MySQL Correlated Subquery

 

MySQL Tutorials

MySQL Tutorials on this website: