Using Subqueries
A subquery is a query (typically enclosed by parentheses) that appears within another SQL data manipulation statement. If evaluated, the subquery gives a value or set of values to the statement. Frequently, the subqueries are used in the WHERE clause. For illustration, the following query returns employees not located in the Chicago:
DECLARE
CURSOR c1 IS SELECT empno, ename FROM emp
WHERE deptno IN (SELECT deptno FROM dept
WHERE loc <> 'CHICAGO');
Using the subquery in the FROM clause, the query below returns the number and name of each department with five or more employees:
DECLARE
CURSOR c1 IS SELECT t1.deptno, dname, "STAFF"
FROM dept t1, (SELECT deptno, COUNT(*) "STAFF"
FROM emp GROUP BY deptno) t2
WHERE t1.deptno = t2.deptno AND "STAFF" >= 5;
While a subquery evaluate only once per table, a correlated subquery evaluate once per row. Consider the query below that returns the name and salary of each employee whose salaries exceed the departmental average. For each row in the emp table, the associated subquery calculate the average salary for that row's department. The row is returned if that row's salaries exceed the average.
DECLARE
CURSOR c1 IS SELECT deptno, ename, sal FROM emp t
WHERE sal > (SELECT AVG(sal) FROM emp WHERE t.deptno = deptno)
ORDER BY deptno;