This Oracle tutorial explains how to use Oracle subqueries with syntax and examples.
In Oracle, 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.
Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries.
For example:
Limitation: Oracle allows up to 255 levels of subqueries in the WHERE clause.
A subquery can also be found in the FROM clause. These are called inline views.
For example:
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.
Oracle allows an unlimited number of subqueries in the FROM clause.
A subquery can also be found in the SELECT clause.
For example:
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 SUM function, COUNT function, MIN function, or MAX function is commonly used in the subquery.