- A subquery is a query within a query for the same or different table.
- The inner query is enclosed in parentheses ().
- The result of the inner query would be given as input to the outer query.
- Subqueries enable you to write queries that select data rows for criteria that are actually developed while the query is executing at run time.
Sub-queries can be used in SELECT, FROM, WHERE, and HAVING clauses.
How to write subqueries in SQL
Types of Sub Queries
There are four broad divisions of subqueries: –
Subquery which returns single row output. They mark the usage of single row comparison operators when used in WHERE conditions.
Subquery returning multiple row output. They make use of multiple row comparison operators like IN, ANY, ALL. There can be sub-queries returning multiple columns also.
Subquery returning multiple column output. They make use of multiple columns and/or multiple rows comparison operators like IN, ANY, ALL.
Correlated subqueries depend on data provided by the outer query. This type of subquery also includes subqueries that use the EXISTS operator to test the existence of data rows satisfying specified criteria.