Академический Документы
Профессиональный Документы
Культура Документы
SUBQUERIES
2
SUBQUERIES
Syntax:
3
SUBQUERIES
Types Of Subqueries
4
SUBQUERIES
Single Row Subqueries
5
SUBQUERIES
Single Row Subqueries
6
SUBQUERIES
Single Row Subqueries
Using group functions
List the employee details whose is earning minimum salary .
7
SUBQUERIES
Single Row Subqueries
Using group functions
8
SUBQUERIES
Multiple Row Subqueries
9
SUBQUERIES
Multiple Row Subqueries
List the employees who earn minimum salaries in their departments
10
SUBQUERIES
Using ANY Operator
List the employees who earns salaries less than any of the
employees of job clerk category
SQL> SELECT ename,sal
FROM emp
WHERE sal <ANY(SELECT sal
FROM emp
WHERE job=CLERK)
AND job<>CLERK;
11
SUBQUERIES
Using ALL Operator
List the employees who earns salaries greater than all the employees
who are working as clerk
SQL> SELECT ename,sal
FROM emp
WHERE sal >ALL(SELECT sal
FROM emp
WHERE job=CLERK)
AND job<>CLERK;
12
ADVANCED SUBQUERIES
Multiple Column Sub Queries
13
PAIRWISE COMPARISION
List the employees who are managed by same manager and belongs to
same departments as the employee with employee number 7654.
SQL> SELECT empno,ename,job,sal
FROM emp
WHERE (mgr,deptno) in(SELECT mgr,deptno
FROM emp
WHERE empno=7654)
AND empno<>7654;
14
USING SUBQUERY IN FROM CLAUSE
List the employee name,job,sal ,deptno and the average salary of their
departments for all the employees who earn more than the average
salaries
of their
SQL> respective
SELECT departments.
a.ename,a.job,a.sal,a.deptno,b.avgsal
FROM emp a,(SELECT deptno,avg(sal) avgsal
FROM emp
GROUP BY deptno) b
WHERE a.deptno=b.deptno
AND a.sal>b.avgsal;
15
CORRELATED SUBQUERIES
16
CORRELATED SUBQUERIES
Syntax:
17
CORRELATED SUBQUERIES
Find the employees who earn more than the average salaries of their
departments
SQL> SELECT ename,job,sal,deptno
FROM emp a
WHERE sal>(SELECT avg(sal)
FROM emp
WHERE deptno = a.deptno);
18
USING EXISTS OPERATORS
19
USING EXISTS OPERATORS
List the employees who have at least one person reporting to them.
20
USING NOT EXISTS OPERATORS
21
CORRELATED UPDATE
22
CORRELATED UPDATE
Denormalise emp table by adding department name column add update the
emp table with all department names using dept table.
23
THE WITH CLAUSE
24
THE WITH CLAUSE
25
THE WITH CLAUSE
SQL> WITH
dept_costs as (SELECT d.dname,sum(sal) dept_total
FROM emp e,dept d
WHERE e.deptno=d.deptno
GROUP BY dname), avg_costs as (
SELECT sum(dept_total)/count(*) as dept_avg
FROM dept_costs)
SELECT * FROM dept_costs
WHERE dept_total>(SELECT dept_avg
FROM avg_costs)
ORDER BY dname;
26