Professional Documents
Culture Documents
18 Subquery
18 Subquery
SUBQUERY
It means placing a query inside the predicate of
another query, and using the inner query’s output in
the predicate’s true and false condition
Or
The value for ‘WHERE’ clause can be obtained
from another ‘SELECT’ clause.
SUBQUERY
Example:
Get the detail of the employee who earns maximum
salary.
Approach: first of all develop the inner query which
calculate the max salary
In the second step write a outer query which show
the details of employee by equating the sal of emp
with the maximum salary outputted by the above
inner query.
SIMPLE SUBQUERY
• SELECT ENAME, EMPNO, DEPTNO,
SAL FROM EMP WHERE SAL =
(SELECT MAX(SAL) FROM EMP);
Inner subquery
Outer subquery
SUBQUERY
• Subqueries are used in the WHERE or
HAVING clause of another SQL statement.
• The subquery must be enclosed in the
paranthesis
• You can reference columns from the outer
query in the inner query.
• Outer column can appear both in SELECT
and WHERE clause
SUBQUERY- NESTING
• The subqueries can be further nested
• There can be 255 subquries in the nest.
• The innermost query is executed first
Nested subquery
• SELECT * FROM EMP WHERE SAL >
(SELECT MAX(SAL) FROM EMP
WHERE DEPTNO = (SELECT DEPT NO
FROM DEPT WHERE RTRIM(DNAME)
= ‘SALES’));
SUBQUERY
SELECT
E.ENAME,E.EMPNO,E.JOB,E.DEPTNO
FROM EMP E WHERE exists (select * from
Emp where deptno=10)
• SELECT
E.ENAME,E.EMPNO,E.JOB,E.DEPTNO
FROM EMP E WHERE EXISTS (SELECT
F.DEPTNO FROM EMP F WHERE
F.MGR =E.EMPNO);
• So what is output of the above query.
EXISTS
SELECT
E.ENAME,E.EMPNO,E.JOB,E.DEPTNO
FROM EMP E
WHERE e.empno in (SELECT distinct mgr
from emp)