Advanced Queries
Advanced Queries
• Multiple-column
Who works in the same department(s) AND under the same boss as Smith? 3
• In this case, the correlated subquery specifically computes, for each employee, the average salary
for the employee’s department
Nested Subqueries
• A nested subquery is executed first and its results are inserted into WHERE clause of a the
main query
• Who works in the same department as King or Smith?
EMP_ID DEPT_ID LAST_NAME SAL
------- ------- ---------- -------
145 80 Russell 14000
SELECT emp_id, dept_id, last_name, salary 146 80 Partners 13500
147 80 Errazuriz 12000
FROM employees e 150 80 Tucker 10000
WHERE dept_id IN (SELECT dept_id 162 80 Vishney 10500
164 80 Marvins 7200
FROM employees 170 80 Fox 9600
WHERE last_name ='King' or 171 80 Smith 7400
173 80 Kumar 6100
last_name = 'Smith'); 100 90 King 24000
101 90 Kochhar 17000
102 90 De Haan 17000
5
• In this case, the nested subquery returns department_id’s for two employees and after that
the parent query evaluates the condition
Inline Views
• An In-line view is a subquery in the FROM clause of a SQL statement just as if it
was a table (acts as a data source)
• What are the employees salary and the MINIMAL salary in
their department?
EMP_ID DEPT_ID LAST_NAME SALARY MIN_SAL
------ ------- ----------- ------ -------
200 10 Whalen 4400 4400
201 20 Hartstein 13000 6000
202 20 Fay 6000 6000
114 30 Raphaely 11000 2500
SELECT e.emp_id a.dept_id, e.last_name, 115 30 Khoo 3100 2500
e.salary, a.min_sal, 116 30 Baida 2900 2500
117 30 Tobias 2800 2500
FROM employees e, 118 30 Himuro 2600 2500
(SELECT MIN(salary)min_sal, dept_id 119 30 Colmenares 2500 2500
203 40 Mavris 6500 6500
FROM employees 121 50 Fripp 8200 2100
GROUP BY dept_id) a 120 50 Weiss 8000 2100
122 6 50 Kaufling 7900 2100
WHERE e.dept_id = a.dept_id 123 50 Vollman 6500 2100
ORDER BY e.dept_id, e.salary DESC; 124 50 Mourgos 5800 2100
184 50 Sarchand 4200 2100
185 50 Bull 4100 2100
192 50 Bell 4000 2100
TOP-N Queries
• use in-line view together with the ROWNUM pseudocolumn
SQL> SELECT str_val, rownum FROM test_rownum WHERE ROWNUM < 4;
STR_VAL ROWNUM
------- -------
ccc 1
bbb 2
aaa 3
SQL> SELECT str_val, rownum FROM test_rownum WHERE ROWNUM < 4 order by 1;
STR_VAL ROWNUM
------- ------- e so rting! 7
UMs befor
aaa 3 OW N
bbb 2 ws gets R
Ro
ccc 1
TOP-N Queries
• use in-line view together with the ROWNUM pseudocolumn
• What are the top 5 most well paid employees?
SELECT * FROM EMP_ID LAST_NAME SALARY
------ ---------- ------
(SELECT emp_id, last_name, salary 100 King 24000
FROM employees 101 Kochhar 17000
ORDER BY salary desc) 102 De Haan 17000
WHERE rownum < 6; 145 Russell 14000
146 Partners 13500