SQL Standard

SQL Co-Related Subqueries

In SQL, a co-related subquery refers to a subquery whose functionality depends on the output of the previous query.

The correlated subquery is run once on each row processed by the outer query.

Syntax

A sample syntax for a correlated subquery in SQL is as shown:

SELECT column1, column2, ....
FROM table1 OUTER
WHERE column1 operator
    (SELECT column1, column2
        FROM table2
        WHERE expr1 = OUTER.expr2);

Note: The parent query can be a select, delete, or update statement.

SQL Correlated Subquery – Example

Consider the table containing product information as shown below:

We can use a correlated subquery to find the product with a quantity equal to the maximum quantity in the table.
We can use a correlated subquery to find the product with a quantity equal to the maximum quantity in the table.

SELECT product_name, product_category, quantity
FROM products tb1
WHERE quantity IN (
    SELECT MAX(tb2.quantity)
    FROM products tb2
    WHERE tb2.product_category = tb1.product_category
    GROUP BY tb2.product_category
)
ORDER BY
    product_name;

The query above should return:

Each product is evaluated by the outer query and then passed to the inner query, which finds the max quantity in that category.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list