Unit 9 - Retrieve Data Using Subqueries
Unit 9 - Retrieve Data Using Subqueries
Using Subqueries
Agenda
• Each row of the main query is compared to values from a multiple-row and
multiple-column subquery:
• Display the details of the employees who are managed by the same manager
and work in the same department as employees with the first name of “John.”
• Display details of those employees who have changed jobs at least twice.
SELECT e.employee_id, last_name,e.job_id
FROM employees e
WHERE 2 <= (SELECT COUNT(*)
FROM job_history
WHERE employee_id = e.employee_id);
Using Subqueries
The EXISTS Operator
• The EXISTS operator tests for existence of rows in the results set of the subquery.
• Helps you to use the same query block in a SELECT statement when it
occurs more than once within a complex query.
• Retrieves the results of a query block and stores it in the user’s temporary
tablespace.
• May improve performance
Using Subqueries
WITH Clause
• Write a query to display the department name and total salaries for those departments
whose total salary is greater than the average salary across departments.
WITH dept_costs AS (
SELECT d.department_name, SUM(e.salary) AS dept_total
FROM employees e JOIN departments d
ON e.department_id = d.department_id
GROUP BY d.department_name),
avg_cost AS (
SELECT SUM(dept_total)/COUNT(*) AS dept_avg
FROM dept_costs) SELECT * FROM dept_costs WHERE dept_total >
(SELECT dept_avg FROM avg_cost)ORDER BY department_name;
Using Subqueries
WITH Clause
WITH RECURSIVE my_crt AS
(
SELECT 1 AS n
UNION ALL
SELECT 1+n FROM my_crt WHERE n<10
)
SELECT * FROM my_crt;
Quiz
• With a correlated subquery, the inner SELECT statement drives the outer
SELECT statement
a)True
b) False
Using Subqueries
Practice 7