Sub topic 12
Naming subqueries with WITH
This chapter assumes you can write inline views and correlated subqueries, and that you know the HR sample schema (EMPLOYEES, DEPARTMENTS). You will name a subquery with the WITH clause, chain several named subqueries, and see how Oracle executes them.
What the WITH clause does
The WITH clause, also called subquery factoring or a common table expression (CTE), gives a query block a name. You define the name at the top of the statement and use it in the main query like a table. It is the same idea as an inline view, but the definition is written first and the logic reads top to bottom.
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id
)
SELECT 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;This returns employees paid above their own department's average. The inline-view version would put the SELECT ... GROUP BY inside the JOIN. With WITH, the main query shows its intent first, and the aggregation is defined once, above it.
A named subquery exists only for the single statement that contains it. It is not stored in the data dictionary and cannot be seen by later statements.
Chaining several named subqueries
You can define several subqueries in one WITH clause, separated by commas. Write WITH once. Each later definition may refer to any earlier one.
WITH dept_totals AS (
SELECT department_id, SUM(salary) AS total_sal
FROM employees
GROUP BY department_id
),
avg_total AS (
SELECT AVG(total_sal) AS avg_total
FROM dept_totals
)
SELECT t.department_id, t.total_sal
FROM dept_totals t
CROSS JOIN avg_total a
WHERE t.total_sal > a.avg_total
ORDER BY t.total_sal DESC;The problem is to find departments whose payroll exceeds the average payroll per department. This needs an aggregate of an aggregate. Without WITH, you would nest one inline view inside another, or repeat the SUM ... GROUP BY block twice. Here dept_totals is written once and used twice: by avg_total and by the main query.
avg_total returns exactly one row, so CROSS JOIN attaches that single value to every department row without needing a join condition.
The diagram shows how the pieces depend on each other.
Naming columns and scope rules
You can list column names after the query name instead of aliasing inside the subquery:
WITH dept_avg (dept_id, avg_sal) AS (
SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id
)
SELECT dept_id, ROUND(avg_sal, 2) AS avg_sal
FROM dept_avg
ORDER BY avg_sal DESC;The column list gives each output column a name, which is useful when the subquery returns an expression without an alias. The number of names must match the number of columns the subquery returns.
These rules apply to the scope of a name:
- A name defined in the
WITHclause is visible in later definitions and in the main query. It is not visible in earlier definitions. Referring forward fails withORA-00942: table or view does not exist, because Oracle looks for a real table of that name. - A query name hides a real table or view of the same name inside that statement. Avoid naming a subquery
employees. - A subquery you define but never reference is allowed. It is simply not executed.
- A named subquery can appear in any place a table can appear in that statement: in a
FROMclause, in a join, or inside another subquery such as anINlist.
Using WITH in the places subqueries live
Because WITH just names a query block, you can use it where you would use a subquery. This lists departments that have a high earner:
SELECT d.department_name
FROM departments d
WHERE d.department_id IN (
WITH high_paid AS (
SELECT department_id
FROM employees
WHERE salary > 10000
)
SELECT department_id FROM high_paid
);This form is legal, but for a single use it adds nothing over a plain IN (SELECT ...). Use WITH when the name makes the statement clearer or when you refer to the block more than once.
How Oracle executes a named subquery
The WITH clause is mainly a readability feature. The performance behavior depends on how many times you reference the name.
- Referenced once. Oracle normally merges the definition into the main query, as if you had written an inline view. The plan is the same as the inline-view version.
- Referenced more than once. Oracle may choose to materialize the result. It runs the subquery once, stores the rows in a temporary table, and reads that table for each reference. In an execution plan this appears as
TEMP TABLE TRANSFORMATIONandLOAD AS SELECT. The optimizer makes this choice by cost.
You can influence the choice with the MATERIALIZE and INLINE hints, placed in the subquery's SELECT:
WITH dept_totals AS (
SELECT /*+ MATERIALIZE */ department_id, SUM(salary) AS total_sal
FROM employees
GROUP BY department_id
)
SELECT department_id, total_sal
FROM dept_totals
WHERE total_sal > (SELECT AVG(total_sal) FROM dept_totals);MATERIALIZE forces the temporary table, which pays off when the subquery is expensive and used several times. INLINE forces the merge, which is better when the main query adds filters that can be pushed into the subquery. These two hints are widely used but are not documented by Oracle, so test them against your version and do not treat them as a stable interface.
A named subquery is not a performance guarantee. Moving code into WITH does not make it faster, and a materialized result has no indexes. Check the execution plan with EXPLAIN PLAN and DBMS_XPLAN.DISPLAY rather than guessing.
Correlation and WITH
A named subquery is defined once, before the main query, so it cannot refer to columns of a table in the main query. This fails:
-- ORA-00904: "D"."DEPARTMENT_ID": invalid identifier
WITH emp_count AS (
SELECT COUNT(*) AS cnt
FROM employees e
WHERE e.department_id = d.department_id
)
SELECT d.department_name, c.cnt
FROM departments d
CROSS JOIN emp_count c;A WITH query is a fixed result set, not a per-row calculation. For per-row logic, keep a correlated subquery in the WHERE or SELECT clause, or use the join-based approach: aggregate in the named subquery grouped by the key, then join on that key, as the dept_avg example does. Use LATERAL or CROSS APPLY from the previous chapters when the inner query must see each outer row.
Recursive WITH
From Oracle Database 11g Release 2, a named subquery can refer to itself. This is a recursive WITH. It has an anchor member, a UNION ALL, and a recursive member, and you must give the column list after the name.
WITH org (employee_id, last_name, manager_id, lvl) AS (
SELECT employee_id, last_name, manager_id, 1
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.last_name, e.manager_id, o.lvl + 1
FROM employees e
JOIN org o ON e.manager_id = o.employee_id
)
SELECT lvl, last_name
FROM org
ORDER BY lvl, last_name;The anchor selects the top-level employee, who has no manager. Each recursive step adds the employees who report to the rows found so far, with lvl increased by one. Oracle also offers CONNECT BY for hierarchies, which handles the same job with different syntax.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ORA-00942` on a query name | The name is used before it is defined, or a comma is missing so the definition is not recognized | Define the name earlier in the list and check the comma placement |
| `ORA-00904` inside a definition | The definition refers to a column of the main query | Group the named subquery by the key and join in the main query |
| `ORA-00918` or `ORA-00957` | Two output columns have the same name | Alias the columns or add a column list |
| Unexpected table is read | The query name matches a real table name | Rename the subquery |
| Extra comma before the main `SELECT` | A trailing comma after the last definition | Remove it |
When to choose WITH
Prefer WITH when:
- The same intermediate result is used more than once in a statement.
- A query has several layers of aggregation, and nested inline views make it hard to read.
- You want to test each step on its own: you can run the body of any definition as a separate query.
Prefer a plain inline view or a join when the block is short and used once, since WITH then adds only length.
Exercise
Write a query with a WITH clause that returns the departments whose average salary is higher than the company-wide average salary. Show department_id and the department average. Use two named subqueries.
Show answer
WITH deptavg AS ( SELECT departmentid, AVG(salary) AS avgsal FROM employees GROUP BY departmentid ), companyavg AS ( SELECT AVG(salary) AS avgsal FROM employees ) SELECT d.departmentid, d.avgsal FROM deptavg d CROSS JOIN companyavg c WHERE d.avgsal > c.avgsal;
Exercise
A colleague writes WITH a AS (SELECT FROM bview), bview AS (SELECT department_id FROM departments) SELECT FROM a; and gets ORA-00942. Why, and how do you fix it?
Show answer
The definition of a refers to bview, which is defined after it. A named subquery can only refer to names defined earlier in the list, so Oracle looks for a real table or view called bview and does not find it. Put the b_view definition first, then a, separated by a comma.