Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Of Correlated Subquery

Tags:

sql

oracle

Even though It has a performance issue, may I know what is the use of correlated subquery?

like image 280
hrishi Avatar asked Nov 25 '09 06:11

hrishi


People also ask

Why do we need correlated subquery?

The subquery is correlated because the number that it produces depends on main. ship_date, a value that the outer SELECT produces. Thus, the subquery must be re-executed for every row that the outer query considers. The query uses the COUNT function to return a value to the main query.

What is the difference between subquery and correlated subquery?

Subqueries can be categorized into two types: A noncorrelated (simple) subquery obtains its results independently of its containing (outer) statement. A correlated subquery requires values from its outer query in order to execute.

When using a correlated subquery What is the requirement?

It has only one operand, which is a subquery (correlated or not). If the subquery returns at least one record, then EXISTS returns TRUE . If the subquery returns no records, EXISTS returns FALSE . In this case, you must use a correlated subquery to get your results.

Which operator is commonly used with correlated subqueries?

Using EXISTS with a Correlated SubqueryEXISTS operator can be used in correlated subqueries also. Using EXISTS the following query display the employee_id, manager_id, first_name and last_name of those employees who manage other employees.


1 Answers

One common usage example: display details of the latest hired employee(s) for each department:

select e.deptno, e.empno, e.ename, e.hiredate, e.sal
from   emp e
where  e.hiredate = (select max(e2.hiredate)
                     from   emp e2
                     where  e2.deptno = e.deptno -- the correlation
                    );
like image 96
Tony Andrews Avatar answered Nov 14 '22 23:11

Tony Andrews