MySQL Subquery
A subquery in MySQL is a query, which is nested into another SQL query and
embedded with SELECT, INSERT, UPDATE or DELETE statement along with the various
operators. We can also nest the subquery with another subquery.
A subquery is known as the inner query, and the query that contains subquery is
known as the outer query.
The inner query executed first gives the result to the outer query, and then the
main/outer query will be performed.
You can use a query like
SELECT category_name FROM categories WHERE category_id =( SELECT MIN(category_id) from movies);
It gives a result
Let’s see how this query works
The above is a form of Row Sub-Query. In such sub-queries the , inner query
can give only ONE result. The permissible operators when work with row
subqueries are [=, >, =, <=, ,!=, ]
The following are the rules to use subqueries:
o Subqueries should always use in parentheses.
o If the main query does not have multiple columns for subquery, then a
subquery can have only one column in the SELECT command.
o We can use various comparison operators with the subquery, such as >, <, =,
IN, ANY, SOME, and ALL. A multiple-row operator is very useful when the
subquery returns more than one row.
o We cannot use the ORDER BY clause in a subquery, although it can be used
inside the main query.
o If we use a subquery in a set function, it cannot be immediately enclosed in a
set function.
The following are the advantages of using subqueries:
o The subqueries make the queries in a structured form that allows us to isolate
each part of a statement.
o The subqueries provide alternative ways to query the data from the table;
otherwise, we need to use complex joins and unions.
o The subqueries are more readable than complex join or union statements.