MySQL Subquery
MySQL Subquery
In this tutorial, we will learn about MySQL Subqueries. MySQL subquery is also called a nested query. It is a query nested inside another SQL query. The subquery is enclosed within the parenthesis inside the outer query.
Syntax
There are three locations in an SQL statement that a subquery can be placed.
- Column
- FROM clause
- WHERE clause
Subqueries are most commonly placed in the WHERE location in a query statement. The simple and basic subquery used with the WHERE clause is as follows:
SELECT [columns_list]
FROM table
WHERE clause = ( Subquery )
The subquery is executed and the subquery results are used by the outer query.
The subquery can also fetch records from another different table. In some cases, it’s much easy to use subquery instead of joining the tables.
Subquery Types
https://www.testingdocs.com/mysql-subquery-categories/
Subquery Placement
https://www.testingdocs.com/mysql-subquery-placement-chart/
Column designated subquery
We can use the column designation part of a query to perform a subquery. The outer query will be run once for each row of the result retrieved from the subquery. Each result must be one column and a maximum of one row.
Let’s perform a query that retrieves the countries that are located for example in the Southern Europe region, with the number of cities per each country. We can use a correlated subquery that calculates the number of cities per country as a column in the outer query.
mysql> SELECT Country.Name,
-> (SELECT COUNT(*) FROM City
-> WHERE City.CountryCode=Country.Code)
-> AS CityCount
-> FROM Country
-> WHERE Country.Region = ‘Southern Europe’;
+——————————-+———–+
| Name | CityCount |
+——————————-+———–+
| Albania | 1 |
| Andorra | 1 |
| Bosnia and Herzegovina | 3 |
| Spain | 59 |
| Gibraltar | 1 |
| Greece | 8 |
| Croatia | 4 |
| Italy | 58 |
| Macedonia | 1 |
| Malta | 2 |
| Portugal | 5 |
| San Marino | 2 |
| Slovenia | 2 |
| Holy See (Vatican City State) | 1 |
| Yugoslavia | 8 |
+——————————-+———–+
15 rows in set (0.00 sec)
—
MySQL Tutorials
MySQL Tutorials on this website:
https://www.testingdocs.com/mysql-tutorials-for-beginners/