0% found this document useful (1 vote)
416 views

Correlated Subqueries

A correlated subquery is evaluated once for each row processed by the parent query, while a non-correlated subquery is evaluated once for the entire parent statement. The EXISTS function tests for the existence of rows returned by a subquery and can be used to check if more than 4 employees exist in a department. NOT EXISTS does the opposite, checking that more than 4 employees do not exist in a department.

Uploaded by

Sofia Hewitt
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
416 views

Correlated Subqueries

A correlated subquery is evaluated once for each row processed by the parent query, while a non-correlated subquery is evaluated once for the entire parent statement. The EXISTS function tests for the existence of rows returned by a subquery and can be used to check if more than 4 employees exist in a department. NOT EXISTS does the opposite, checking that more than 4 employees do not exist in a department.

Uploaded by

Sofia Hewitt
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

CORRELATED SUBQUERIES A sub query is evaluated once for the entire parent statement where as a correlated subquery is evaluated

once for every row processed by the parent statement. Ex: SQL> select distinct deptno from emp e where 5 <= (select count(ename) from emp where e.deptno = deptno); DEPTNO ---------20 30 EXISTS Exists function is a test for existence. This is a logical test for the return of rows from a query. Ex: Suppose we want to display the department numbers which has more than 4 employees. SQL> select deptno, count(*) from emp group by deptno having count(*) > 4; DEPTNO COUNT(*) --------- ---------20 5 30 6 From the above query can you want to display the names of employees? SQL> select deptno, ename, count(*) from emp group by deptno, ename having count(*) > 4; no rows selected The above query returns nothing because combination of deptno and ename never return more than one count. The solution is to use exists which follows. SQL> select deptno, ename from emp e1 where exists (select * from emp e2 where e1.deptno=e2.deptno group by e2.deptno having count(e2.ename) > 4) order by deptno, ename; DEPTNO ENAME ---------- ---------20 ADAMS 20 FORD 20 JONES

20 20 30 30 30 30 30 30

SCOTT SMITH ALLEN BLAKE JAMES MARTIN TURNER WARD

NOT EXISTS SQL> select deptno, ename from emp e1 where not exists (select * from emp e2 where e1.deptno=e2.deptno group by e2.deptno having count(e2.ename) > 4) order by deptno, ename; DEPTNO ENAME --------- ---------10 CLARK 10 KING 10 MILLER

You might also like