Sub topic 12
Naming Subqueries with `WITH`
This chapter assumes you know basic SELECT, WHERE, GROUP BY, aggregate functions, and joins. It also assumes you have used Oracle's EMPLOYEES and DEPARTMENTS tables.
A WITH clause names a subquery before the main query runs. The named subquery is called a common table expression, or CTE. A CTE works like a temporary result set that exists only for one SQL statement.
Why use a CTE?
A deeply nested subquery can be difficult to read. A CTE gives the intermediate result a meaningful name and places its logic before the main query.
Suppose you want employees whose salary is above the average salary in their department. You can calculate the departmental averages in a CTE and then join that result to EMPLOYEES:
WITH dept_avg AS (
SELECT department_id,
AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id
)
SELECT e.employee_id,
e.last_name,
e.salary,
a.avg_sal
FROM employees e
JOIN dept_avg a
ON a.department_id = e.department_id
WHERE e.salary > a.avg_sal
ORDER BY e.department_id, e.salary DESC;The WITH clause is evaluated as part of the statement. It does not create a permanent table, and dept_avg cannot be queried after this statement finishes.
How a CTE is structured
The general form is:
WITH query_name AS (
SELECT ...
)
SELECT ...
FROM query_name;The CTE must appear immediately before the SELECT, INSERT, UPDATE, or DELETE statement that uses it. The main statement can refer to the CTE like a table or view.
You can define more than one CTE. Later CTEs can refer to earlier ones:
WITH dept_avg AS (
SELECT department_id,
AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id
),
above_avg AS (
SELECT e.last_name,
e.department_id,
e.salary
FROM employees e
JOIN dept_avg a
ON a.department_id = e.department_id
WHERE e.salary > a.avg_sal
)
SELECT d.department_name,
x.last_name,
x.salary
FROM above_avg x
JOIN departments d
ON d.department_id = x.department_id
ORDER BY d.department_name, x.salary DESC;This separates the calculation into named steps. Each step can be tested as a separate SELECT while you develop the statement.
Reuse and optimizer behavior
A CTE can be referenced more than once in the same statement. This is useful when several parts of a query need the same intermediate result. However, a CTE does not automatically force Oracle to store its rows. The optimizer may merge the CTE into the surrounding query or materialize it internally.
Therefore, use WITH mainly to express the logic clearly. Do not assume that naming a subquery makes it faster. Check the execution plan when performance matters.
Choosing `WITH` or a join
A CTE and an inline view can express similar logic. Use a CTE when the intermediate result deserves a name, has several steps, or is reused. Use a direct join when the operation is short and already easy to understand.
Exercise
Write a query using a CTE named dept_max that returns each department ID and the last name and salary of every employee who earns the maximum salary in that department.
Show answer
WITH dept_max AS (SELECT department_id, MAX(salary) AS max_sal FROM employees GROUP BY department_id) SELECT e.department_id, e.last_name, e.salary FROM employees e JOIN dept_max m ON m.department_id = e.department_id AND m.max_sal = e.salary;