Sub topic 2
Inline views in the FROM clause
This chapter assumes you know SELECT, WHERE, ORDER BY, GROUP BY, joins, and aggregate functions such as AVG and COUNT. The examples use the Oracle HR sample schema (EMPLOYEES and DEPARTMENTS).
An inline view is a subquery in the FROM clause. Oracle treats its result as a temporary table for the duration of the statement. You must give it an alias.
SELECT d.department_name, s.avg_sal
FROM departments d
JOIN (SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id) s
ON s.department_id = d.department_id;The inline view computes one average per department. The outer query joins that result to DEPARTMENTS.
Scalar subqueries in the SELECT list
A scalar subquery returns exactly one column and at most one row. It can sit anywhere a single value can, including the SELECT list.
SELECT d.department_name,
(SELECT COUNT(*)
FROM employees e
WHERE e.department_id = d.department_id) AS headcount
FROM departments d;> Note: If the subquery returns more than one row, Oracle raises ORA-01427: single-row subquery returns more than one row.
Correlated subqueries
A correlated subquery refers to a column of the outer query. Oracle evaluates it once for each outer row. The following query returns employees paid more than the average of their own department.
SELECT e.employee_id, e.last_name, e.salary, e.department_id
FROM employees e
WHERE e.salary > (SELECT AVG(i.salary)
FROM employees i
WHERE i.department_id = e.department_id);EXISTS and NOT EXISTS
EXISTS is true when the subquery returns at least one row. The columns in its SELECT list do not matter, so SELECT 1 is a common choice. The first query below lists departments that have employees. The second lists departments that have none.
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);
SELECT d.department_name
FROM departments d
WHERE NOT EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);Oracle stops evaluating the subquery as soon as it finds one matching row. This short-circuit is why EXISTS often performs well on large tables.
:::
Exercise
Rewrite the correlated query above, which lists employees paid more than their department's average, using an inline view instead.
Show answer
SELECT e.lastname, e.salary FROM employees e JOIN (SELECT departmentid, AVG(salary) AS avgsal FROM employees GROUP BY departmentid) a ON a.departmentid = e.departmentid WHERE e.salary > a.avg_sal;