correlated subquery sql code example

Example 1: correlated subquery

A correlated subquery is a way of reading values in each row
and comparing those values in each row with related data.

A correlated subquery is evaluated once for each row
processed by the parent query.
i.e. the subquery returns a value for each row
processed by the parent query unlike the normal subquery which executes
only once and returns the data to the parent query for processing.

SELECT last_name, salary, department_id
FROM employees outer
WHERE salary > (SELECT AVG(salary)
                FROM employees
                WHERE department_id = outer.department_id
               );

Here the inner query (correlated subquery) generates
the avg salary for each department_id processed by the outer query.

Example 2: What is Correlated Subquery in DBMS?

SELECT * from EMP WHERE ‘RIYA’ IN (SELECT Name from DEPT WHERE EMP.EMPID=DEPT.EMPID);

Tags:

Sql Example