Sub topic 5
Inline views in the FROM clause
An inline view is a subquery placed in the FROM clause. Oracle runs it, treats its result as a temporary table for the rest of the statement, and discards it afterward. This chapter assumes you can write joins and GROUP BY queries, and that you know the HR sample schema (EMPLOYEES, DEPARTMENTS). It also assumes you have read the earlier chapters on single-row subqueries and on where subqueries can appear.
What an inline view is
A normal subquery in WHERE produces a value or a set of values for a comparison. An inline view produces a full row source: any number of rows and columns that you can join, filter, and select from.
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 query has two layers:
- The inner query groups
EMPLOYEESby department and returns one row per department withDEPARTMENT_IDandAVG_SAL. - The outer query joins that result to
DEPARTMENTSas ifswere a table.
An inline view is not stored in the data dictionary, unlike a view created with CREATE VIEW. It exists only for the statement that contains it.
Aliases for the view and its columns
Oracle lets you omit the alias on an inline view, but you should always give one. Without it you cannot qualify the view's columns, and a join against two unnamed row sources quickly becomes ambiguous.
Column names matter more. A column that comes from an expression takes the expression text as its name, so AVG(salary) becomes a column called AVG(SALARY). The outer query cannot refer to that name without double quotes. Give every expression an alias inside the view.
-- Fails with ORA-00904: "S"."AVG_SAL": invalid identifier
SELECT d.department_name, s.avg_sal
FROM departments d
JOIN (SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id) s
ON s.department_id = d.department_id;Adding AS avg_sal inside the inner query, as in the first example, fixes it.
A second error appears when an inline view selects two columns with the same name, for example from a join, and the outer query uses SELECT * or refers to the name. Oracle raises ORA-00918 (column ambiguously defined). Alias one of the columns inside the view.
Comparing rows to an aggregate
A common use is comparing each detail row with a group-level figure. A scalar subquery in WHERE can do this for one company-wide average. For a per-department average, an inline view joined on the department computes every average once.
SELECT e.last_name, e.salary, s.avg_sal,
e.salary - s.avg_sal AS above_avg
FROM employees e
JOIN (SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id) s
ON s.department_id = e.department_id
WHERE e.salary > s.avg_sal
ORDER BY above_avg DESC;This is the join version of the correlated query you will meet in a later chapter. The inline view is evaluated as a set, and the join matches each employee to the right average. The result also exposes AVG_SAL as a column, which a plain WHERE subquery cannot do.
Employees with a NULL department (for example, one without a department assignment) fall into a group with a NULL key. An inner join on department_id drops them, because NULL = NULL is not true. Use an outer join if you need to keep such rows.
Filtering on calculated values
WHERE is evaluated before SELECT, so you cannot filter on a column alias or on a window function in the same query block. An inline view moves the calculation to an inner block, and the outer block then filters on it as an ordinary column.
SELECT department_id, last_name, salary
FROM (SELECT department_id, last_name, salary,
RANK() OVER (PARTITION BY department_id
ORDER BY salary DESC) AS sal_rank
FROM employees)
WHERE sal_rank = 1;The query returns the top earner of each department, with ties. Writing WHERE RANK() OVER (...) = 1 directly raises ORA-30483 (window functions are not allowed here). The same wrapping technique works for any alias you want to filter on.
Top-N queries
Inline views are also the standard way to take the first few rows of a sorted result in versions before 12c. The pattern is to sort in the inner query and apply ROWNUM outside.
SELECT last_name, salary
FROM (SELECT last_name, salary
FROM employees
ORDER BY salary DESC)
WHERE ROWNUM <= 3;The order of the layers matters. ROWNUM is assigned as rows are produced, before the ORDER BY of the same query block is applied. This version looks right but returns the wrong rows:
-- Wrong: picks any three rows, then sorts them
SELECT last_name, salary
FROM employees
WHERE ROWNUM <= 3
ORDER BY salary DESC;In Oracle 12c and later you can write the same request without an inline view:
SELECT last_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 3 ROWS ONLY;Prefer FETCH FIRST on 12c and later. You still need the inline-view form for older databases and for code you maintain that uses it.
Be aware of how the two row-limiting forms treat ties. ROWNUM <= 3 and FETCH FIRST 3 ROWS ONLY cut off at exactly three rows, so a tie at the boundary is broken arbitrarily. FETCH FIRST 3 ROWS WITH TIES and the RANK() approach above keep tied rows.
Rules and limits
| Rule | Detail |
|---|---|
| Parentheses | The inline view must be enclosed in parentheses. |
| `ORDER BY` | Allowed inside an inline view. It only affects the outer result when the outer query uses it, as with `ROWNUM` or `FETCH FIRST`. Do not rely on it to order the final output. |
| Outer references | A plain inline view cannot refer to columns of other tables in the same `FROM` clause. Doing so raises ORA-00904. Use `LATERAL` or `CROSS APPLY` (a later chapter). |
| Column names | Expression columns need aliases, and duplicate names must be avoided. |
| Nesting | Inline views can contain other inline views. Depth beyond two or three levels is usually a sign to use `WITH`. |
What Oracle does with an inline view
The optimizer does not always run the inner query first and materialize it. For simple views, it merges the inner query into the outer one, which gives it more join orders to consider. Views that contain GROUP BY, DISTINCT, analytic functions, or ROWNUM are harder to merge, and Oracle often evaluates them as a separate step. You can see the result in the execution plan as a VIEW operation. Write the query for clarity first, then read the plan if performance is a concern.
EXPLAIN PLAN FOR
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;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Inline view or WITH
An inline view and a WITH subquery express the same thing for a single use. Choose by readability:
- Use an inline view when the logic is short and used once.
- Use
WITHwhen you want a meaningful name, when the same result is used more than once, or when nesting makes theFROMclause hard to read.
Common mistakes
- Forgetting to alias an aggregate in the inner query, then getting ORA-00904 in the outer query.
- Applying
ROWNUMin the same block as theORDER BYit is meant to follow. - Assuming the order of an inner
ORDER BYis preserved after a join. - Joining on a key that can be
NULLand losing rows silently. - Using
SELECT *from a view built on a join and hitting ORA-00918.
Exercise
Write a query that lists each department's name and its highest salary, but only for departments whose highest salary is above 12000. Use an inline view for the aggregation, and name the aggregate column in the inner query.
Show answer
SELECT d.departmentname, s.maxsal FROM departments d JOIN (SELECT departmentid, MAX(salary) AS maxsal FROM employees GROUP BY departmentid) s ON s.departmentid = d.departmentid WHERE s.maxsal > 12000; The alias max_sal inside the view lets the outer WHERE and SELECT refer to it. A HAVING clause in the inner query would give the same result.
Exercise
A colleague writes SELECT last_name, salary FROM employees WHERE ROWNUM <= 5 ORDER BY salary DESC to find the five highest-paid employees. Why is this wrong, and how do you fix it using an inline view?
Show answer
ROWNUM is assigned before ORDER BY is applied in the same query block, so the query takes any five rows and only then sorts them. Move the sort into an inline view and apply ROWNUM outside: SELECT lastname, salary FROM (SELECT lastname, salary FROM employees ORDER BY salary DESC) WHERE ROWNUM <= 5; On Oracle 12c and later, ORDER BY salary DESC FETCH FIRST 5 ROWS ONLY also works.