Sub topic 13
LATERAL and CROSS APPLY
This chapter assumes you can write correlated subqueries, use inline views in the FROM clause, and join tables. It also assumes you know the Oracle HR sample schema (EMPLOYEES, DEPARTMENTS). Correlated inline views build on all three. The CROSS APPLY and OUTER APPLY syntax needs Oracle Database 12c or later.
The problem: an inline view cannot see its neighbours
A correlated subquery in the WHERE clause can refer to a column of the outer query. A plain inline view in the FROM clause cannot refer to the tables listed beside it. Oracle evaluates the inline view on its own, before the join.
SELECT d.department_name, t.last_name
FROM departments d
JOIN (SELECT e.last_name
FROM employees e
WHERE e.department_id = d.department_id) t
ON 1 = 1;This fails with ORA-00904: invalid identifier, because d is not visible inside the parentheses. Without a correlated inline view, you can't ask for "the two highest-paid employees of each department" in one nested step. A WHERE rownum <= 2 inside the inline view limits the whole result, not each department.
Before 12c, the usual workaround was an analytic function such as ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC), wrapped in another inline view. That still works. LATERAL and APPLY give a more direct way to express the same idea.
LATERAL: an inline view that can see earlier tables
The keyword LATERAL in front of an inline view allows it to refer to tables that appear before it in the FROM clause.
SELECT d.department_name, t.last_name, t.salary
FROM departments d
CROSS JOIN LATERAL (SELECT e.last_name, e.salary
FROM employees e
WHERE e.department_id = d.department_id
ORDER BY e.salary DESC, e.employee_id
FETCH FIRST 2 ROWS ONLY) t;For each row of departments, Oracle runs the inline view with that row's department_id. The two highest-paid employees of that department come back, and they are joined to the department row. The FETCH FIRST 2 ROWS ONLY clause now applies per department, not to the whole query.
The added e.employee_id in the ORDER BY makes the result deterministic when two employees have the same salary.
A lateral inline view can be used with these join forms:
CROSS JOIN LATERAL (...): an inner join with no join condition, so departments with no matching rows disappear.INNER JOIN LATERAL (...) ON condition: the same, with an extra join condition.LEFT OUTER JOIN LATERAL (...) ON condition: outer rows are kept even when the lateral view returns nothing.
Oracle also accepts the older comma form FROM departments d, LATERAL (...) t. The explicit join keywords make the intent clearer.
CROSS APPLY and OUTER APPLY
CROSS APPLY is shorthand for CROSS JOIN LATERAL. Oracle supports it from 12c, and it is the same keyword used in SQL Server.
SELECT d.department_name, t.last_name, t.salary
FROM departments d
CROSS APPLY (SELECT e.last_name, e.salary
FROM employees e
WHERE e.department_id = d.department_id
ORDER BY e.salary DESC, e.employee_id
FETCH FIRST 2 ROWS ONLY) t;OUTER APPLY is the outer-join version. It keeps every row of the left table and fills the right-hand columns with NULL when the inline view returns no rows.
SELECT d.department_name, t.last_name, t.salary
FROM departments d
OUTER APPLY (SELECT e.last_name, e.salary
FROM employees e
WHERE e.department_id = d.department_id
ORDER BY e.salary DESC, e.employee_id
FETCH FIRST 2 ROWS ONLY) t
ORDER BY d.department_name, t.salary DESC;In the HR schema, some departments have no employees. With CROSS APPLY they vanish from the result. With OUTER APPLY they appear once, with NULL in last_name and salary.
| Form | Rows from the left table with no match | Equivalent join |
|---|---|---|
| `CROSS APPLY (...)` | Dropped | `CROSS JOIN LATERAL (...)` |
| `OUTER APPLY (...)` | Kept, right columns are NULL | `LEFT OUTER JOIN LATERAL (...) ON (1 = 1)` |
The ON (1 = 1) condition is needed because Oracle requires an ON clause on an explicit outer join. For a lateral view, the correlation inside the view does the real matching.
Lateral views versus scalar subqueries
A scalar subquery in the SELECT list returns exactly one column and at most one row. If you need three values from the same lookup, you must repeat the correlated subquery three times. A lateral view returns several columns in one pass.
SELECT d.department_name,
s.headcount,
s.max_salary,
s.avg_salary
FROM departments d
CROSS APPLY (SELECT COUNT(*) AS headcount,
MAX(e.salary) AS max_salary,
ROUND(AVG(e.salary), 2) AS avg_salary
FROM employees e
WHERE e.department_id = d.department_id) s;An aggregate query without GROUP BY always returns exactly one row, even when no employees match. COUNT(*) returns 0 and the other columns are NULL. So CROSS APPLY keeps every department here, and OUTER APPLY would give the same result.
| Technique | Columns per row | Rows per outer row | Can use ORDER BY with FETCH FIRST |
|---|---|---|---|
| Scalar subquery in SELECT | One | At most one (otherwise ORA-01427) | Yes, but only one column comes back |
| Plain inline view | Many | Many | Yes, but it cannot see outer columns |
| LATERAL or APPLY inline view | Many | Zero, one or many | Yes, and the limit is per outer row |
Top-N per group with ties
Use FETCH FIRST n ROWS WITH TIES when equal values at the cutoff should all be returned.
SELECT d.department_name, t.last_name, t.salary
FROM departments d
CROSS APPLY (SELECT e.last_name, e.salary
FROM employees e
WHERE e.department_id = d.department_id
ORDER BY e.salary DESC
FETCH FIRST 2 ROWS WITH TIES) t;If three employees in one department share the second-highest salary, all three are returned along with the top earner. Without a tie-breaking column, ONLY would pick two of them in an unspecified order, so the result could change between runs.
What can go wrong
- Left-to-right order matters. The lateral view can refer only to tables that appear before it in the FROM clause. A reference to a table listed after it raises ORA-00904.
- Correlation inside the view is your job.
CROSS APPLYdoes not match rows by itself. If you forget theWHERE e.department_id = d.department_id, every department is paired with the top two employees of the whole company. - Cost grows with the outer row count. Conceptually the inner query runs once per outer row. If the outer table has millions of rows and the inner query has no useful index on its correlation column, the query will be slow. An index on
employees(department_id, salary)helps the example above. - The optimizer may transform the query. Oracle can sometimes merge a lateral view into the main query or rewrite it as a join, so the real execution can differ from the row-by-row model. Treat the model as the meaning of the query, and check the execution plan for the actual cost.
- Portability.
CROSS APPLYandOUTER APPLYlook familiar to SQL Server users, butLATERALis the standard SQL keyword and is also used in PostgreSQL and MySQL. If a script must run on several databases,LATERALis the safer choice.
When to choose a lateral view
Use a lateral view or APPLY when you need:
- the top N rows per group, with a different sort or filter for each outer row;
- several computed columns from one correlated lookup, instead of repeating scalar subqueries;
- a table function or a derived set that depends on a column from an earlier table.
Prefer a join with GROUP BY or an analytic function when you need a simple aggregate over every group. A single pass over the table is usually cheaper than a per-row lookup. Prefer EXISTS when you only need to test whether a related row exists.
Exercise
Write a query that lists every department name with the date of its most recent hire (the largest HIRE_DATE among its employees). Departments with no employees must still appear, with NULL in the date column. Which APPLY form do you need, and why?
Show answer
Use OUTER APPLY with a one-row inline view that sorts by hire date. SELECT d.departmentname, t.hiredate FROM departments d OUTER APPLY (SELECT e.hiredate FROM employees e WHERE e.departmentid = d.departmentid ORDER BY e.hiredate DESC FETCH FIRST 1 ROW ONLY) t; OUTER APPLY is needed because CROSS APPLY would drop departments for which the inline view returns no row. (A MAX(e.hire_date) aggregate inside the view would also return one row per department, so CROSS APPLY would work for that variant.)
Exercise
A colleague writes FROM departments d JOIN (SELECT AVG(e.salary) AS avgsal FROM employees e WHERE e.departmentid = d.department_id) s ON 1 = 1 and gets ORA-00904. What are two ways to fix it?
Show answer
Either add LATERAL before the inline view and use CROSS JOIN LATERAL (or CROSS APPLY), so the view may refer to d.departmentid. Or remove the correlation: group the inline view by departmentid (SELECT departmentid, AVG(salary) AS avgsal FROM employees GROUP BY departmentid) and join it with ON s.departmentid = d.department_id.