This tutorial explains how to use subqueries in MySQL with syntax and examples.
What is a subquery in MySQL?
In MySQL, a subquery is a query within a query. You can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.
In MySQL, a subquery is also called an INNER QUERY or INNER SELECT.
In MySQL, the main query that contains the subquery is also called the OUTER QUERY or OUTER SELECT.
Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries.
The subquery portion of the SELECT statement above is:
This subquery allows you to find all site_name values from the address_book table that have an address_book_id less than 50. The subquery is then used to filter the results from the main query using the IN condition.
This subquery could have alternatively been written as an INNER join as follows:
This INNER JOIN would run more efficiently than the original subquery. It is important to note, though, that not all subqueries can be rewritten using joins.
A subquery can also be found in the FROM clause. These are called inline views.
In this example, we've created a subquery in the FROM clause as follows:
This subquery has been aliased with the name subquery1. This will be the name used to reference this subquery or any of its fields.
A subquery can also be found in the SELECT clause. These are generally used when you wish to retrieve a calculation using an aggregate function such as the SUM, COUNT, MIN, MAX , or AVG function, but you do not want the aggregate function to apply to the main query.
In this example, we've created a subquery in the SELECT clause as follows:
The subquery has been aliased with the name subquery2. This will be the name used to reference this subquery or any of its fields.
The trick to placing a subquery in the SELECT clause is that the subquery must return a single value. This is why an aggregate function such as the SUM, COUNT, MIN, MAX, or AVG function is commonly used in the subquery.