Oracle Correlated SubQuery
Oracle Correlated SubQuery
The Oracle correlated subquery which is a subquery whose some clauses refer to the
column expressions in the outer query.
The following query returns the cheapest products from the products table using
a subquery in the WHERE clause.
SELECT
product_id,
product_name,
list_price
FROM
products
WHERE
list_price =(
SELECT
MIN( list_price )
FROM
products
);
Code language: SQL (Structured Query Language) (sql)
SELECT
MIN( list_price )
FROM
products;
Code language: SQL (Structured Query Language) (sql)
Unlike the above subquery, a correlated subquery is a subquery that uses values
from the outer query. In addition, a correlated subquery may be evaluated once for
each row selected by the outer query. Because of this, a query that uses a correlated
subquery could be slow.
The following query finds all products whose list price is above average for their
category.
SELECT
product_id,
product_name,
list_price
FROM
products p
WHERE
list_price > (
SELECT
AVG( list_price )
FROM
products
WHERE
category_id = p.category_id
);
Code language: SQL (Structured Query Language) (sql)
In the above query, the outer query is:
SELECT
product_id,
product_name,
list_price
FROM
products p
WHERE
list_price >
Code language: SQL (Structured Query Language) (sql)
SELECT
AVG( list_price )
FROM
products
WHERE
category_id = p.category_id
Code language: SQL (Structured Query Language) (sql)
For each product from the products table, Oracle has to execute the correlated
subquery to calculate the average price by category.
The following query returns all products and the average standard cost based on the
product category:
SELECT
product_id,
product_name,
standard_cost,
ROUND(
(
SELECT
AVG( standard_cost )
FROM
products
WHERE
category_id = p.category_id
),
2
) avg_standard_cost
FROM
products p
ORDER BY
product_name;
Code language: SQL (Structured Query Language) (sql)
For each product from the products table, Oracle executed the correlated subquery to
calculate the average standard of cost for the product category.
Note that the above query used the ROUND() function to round the average
standard cost to two decimals.
We usually use a correlated subquery with the EXISTS operator. For example, the
following statement returns all customers who have no orders: