A nested SELECT statement is also called a subquery, in the form of:
Select name from BBC where region = (select Region from BBC where name = ' Brazil ')
The query result of a SELECT statement can be the input value of another statement.
The above SQL statement is for all countries that are in the same region as ' Brazil ' (Brazil).
A subquery can appear not only in the WHERE clause, but also in the FROM clause, as a temporary table, or in a select list, which is returned as a field value. In this section we only describe subqueries in the WHERE clause.
Using subqueries in the WHERE clause, there is an error that is easy to make in actual use.
Usually, as in the example above, nested statements are always compared to a value.
Statement (SELECT region from BBC WHERE name = ' Brazil ') should return only one region, that is, ' Americas '. But what happens if we insert another area in the table for Europe and the name of the country as Brazil?
This will result in a run-time error for the statement. Because the syntax of this SQL statement is correct, the database engine starts executing, but there is an error when executing to an external statement.
Because the external statement at this time is like the SELECT name from BBC WHERE region = (' Americas ', ' Europe '), this statement is certainly an error.
Then there is no way to solve the problem, of course. There are some SQL query conditions that allow you to manipulate list values (that is, multiple values).
For example, the "in" operator allows you to test whether a value is in a list.
The following statement can be safely executed without error, regardless of how many of the tables contain Brazils records
SELECT name from BBC WHERE region in
(SELECT region from BBC WHERE name = ' Brazil ')
Ok
Let's take a look at some concrete examples,
I. Giving the name of a country with a population more than Russia (Russia)
SELECT name from BBC
WHERE population>
(SELECT population from BBC
WHERE name= ' Russia ')
Ii. all information for all countries in the area of ' India ' (India), ' Iran ' (Iran)
SELECT * from BBC
WHERE Region in
(SELECT region from BBC
WHERE name in (' India ', ' Iran ')
Third, a European country with a per capita GDP exceeding ' United Kingdom ' (UK).
SELECT name from BBC
WHERE region= ' Europe ' and gdp/population >
(SELECT gdp/population from BBC
WHERE name= ' United Kingdom ')