A subquery, also referred to as an inner select or inner query, is an SQL query nested within an outer SQL query, also referred to as an outer select or outer query.

Occurrence of a subquery

A subquery can occur in the following places:

  • Within a WHERE clause
  • Within a SELECT clause
  • Within a FROM clause

Usually a subquery is within the WHERE clause. The subquery is executed first before the outer query. Subqueries can be used not only with the areas mentioned above, they can also be used with INSERT, DELETE, and UPDATE in the following cases:

  • Find out if there any rows that have been selected through a query.
  • Find out if the query that is outputted included an expression.
  • Compare an expression that you have to the output of a query.

When to use a subquery

A subquery is needed when you need to use the results of one query in another query.