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. MySQL allows us to use subquery anywhere, but it must be closed within parenthesis. All subquery forms and operations supported by the SQL standard will be supported in MySQL also.

The following are the rules to use subqueries:

  • Subqueries should always use in parentheses.
  • If the main query does not have multiple columns for subquery, then a subquery can have only one column in the SELECT command.
  • 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.
  • We cannot use the ORDER BY clause in a subquery, although it can be used inside the main query.
  • 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:

  • The subqueries make the queries in a structured form that allows us to isolate each part of a statement.
  • The subqueries provide alternative ways to query the data from the table; otherwise, we need to use complex joins and unions.
  • The subqueries are more readable than complex join or union statements.

MySQL Subquery Syntax

The following is the basic syntax to use the subquery in MySQL:

MySQL Subquery Example

Let us understand it with the help of an example. Suppose we have a table named "employees" that contains the following data:

Table: employees

MySQL Subquery

Following is a simple SQL statement that returns the employee detail whose id matches in a subquery:

This query will return the following output:

MySQL Subquery

MySQL Subquery with Comparison Operator

A comparison operator is an operator used to compare values and returns the result, either true or false. The following comparison operators are used in MySQL <, >, =, <>, <=>, etc. We can use the subquery before or after the comparison operators that return a single value. The returned value can be the arithmetic expression or a column function. After that, SQL compares the subquery results with the value on the other side of the comparison operator. The below example explains it more clearly:

Following is a simple SQL statement that returns the employee detail whose income is more than 350000 with the help of subquery:

This query first executes the subquery that returns the employee id whose income > 350000. Second, the main query will return the employees all details whose employee id are in the result set returned by the subquery.

After executing the statement, we will get the below output, where we can see the employee detail whose income>350000.

MySQL Subquery

Let us see an example of another comparison operator, such as equality (=) to find employee details with maximum income using a subquery.

It will give the output where we can see two employees detail who have maximum income.

MySQL Subquery

MySQL Subquery with IN or NOT-IN Operator

If the subquery produces more than one value, we need to use the IN or NOT IN operator with the WHERE clause. Suppose we have a table named "Student" and "Student2" that contains the following data:

Table: Student

MySQL Subquery

Table: Student2

MySQL Subquery

The following subquery with NOT IN operator returns the student detail who does not belong to Los Angeles City from both tables as follows:

After execution, we can see that the result contains the student details not belonging to Los Angeles City.

MySQL Subquery

MySQL Subquery in the FROM Clause

If we use a subquery in the FROM clause, MySQL will return the output from a subquery is used as a temporary table. We called this table as a derived table, inline views, or materialized subquery.

The following subquery returns the maximum, minimum, and average number of items in the order table:

It will give the output as follows:

MySQL Subquery

MySQL Correlated Subqueries

A correlated subquery in MySQL is a subquery that depends on the outer query. It uses the data from the outer query or contains a reference to a parent query that also appears in the outer query. MySQL evaluates it once from each row in the outer query.

In the above query, we select an employee name and city whose income is higher than the average income of all employees in each city.

MySQL Subquery

The subquery executes for every city of the specified table because it will change for every row. Therefore, the average income will also be changed. Then, the main query filters employee detail whose income is higher than the average income from the subquery.

MySQL Subqueries with EXISTS or NOT EXISTS

The EXISTS operator is a Boolean operator that returns either true or false result. It is used with a subquery and checks the existence of data in a subquery. If a subquery returns any record at all, this operator returns true. Otherwise, it will return false. The NOT EXISTS operator used for negation that gives true value when the subquery does not return any row. Otherwise, it returns false. Both EXISTS and NOT EXISTS used with correlated subqueries. The following example illustrates it more clearly. Suppose we have a table customer and order that contains the data as follows:

MySQL Subquery

The below SQL statements uses EXISTS operator to find the name, occupation, and age of the customer who has placed at least one order.

This statement uses NOT EXISTS operator that returns the customer details who have not placed an order.

We can see the below output to understand the above queries result.

MySQL Subquery

To read more information about the EXISTS operator, click here.

MySQL ROW Subqueries

It is a subquery that returns a single row where we can get more than one column values. We can use the following operators for comparing row subqueries =, >, <, >=, <=, <>, !=, <=>. Let us see the following example:

If given row has cust_id, occupation values equal to the order_id, order_date values of any rows in the first table, the WHERE expression is TRUE, and each query returns those first table rows. Otherwise, the expression is FALSE, and the query produces an empty set, which can be shown in the below image:

MySQL Subquery

MySQL Subqueries with ALL, ANY, and SOME

We can use a subquery which is followed by the keyword ALL, ANY, or SOME after a comparison operator. The following are the syntax to use subqueries with ALL, ANY, or SOME:

The ALL keyword compares values with the value returned by a subquery. Therefore, it returns TRUE if the comparison is TRUE for ALL of the values returned by a subquery. The ANY keyword returns TRUE if the comparison is TRUE for ANY of the values returned by a subquery. The ANY and SOME keywords are the same because they are the alias of each other. The following example explains it more clearly:

We will get the output as follows:

MySQL Subquery

If we use ALL in place of ANY, it will return TRUE when the comparison is TRUE for ALL values in the column returned by a subquery. For example:

We can see the output as below:

MySQL Subquery