Professional Documents
Culture Documents
Summary
Inline views
Nested views
Subquery factoring aka common table expressions or the with clause.
Scalar subqueries
Background
Inline View
An inline view goes in the from clause of your statement. This replaces a regular database table. For
example, the bolded section below is an inline view:
select * from (
select * from subquery
) inline_view
You can place any number of inline views inside each other. For example:
select * from (
select * from (
select * from (
select * from subquery
) inline_view_1
) inline_view_2
) inline_view_3;
Though nesting more than one or two inline views makes your query hard to understand!
Inline views enable you to use the results of one query in another.
Nested Subquery
A nested subquery goes in the where clause of a statement. This allows you to filter rows based on
the output of another query.
You can do this with either IN or EXISTS. For each of these, the nested subquery can be correlated or
uncorrelated.
IN
This compares a column in the parent table against a value from the subquery. For example:
select *
from parent_tab pt
where pt.col in (
select ins.col from in_subquery ins
)
Exists
This is true if the subquery returns at least one row. It takes the form:
select *
from parent_tab pt
where exists (
select null from exists_subquery us
)
Uncorrelated Subquery
select *
from parent_tab pt
where pt.col in (
select us.col from uncorrelated_subquery us
)
Correlated Subquery
select *
from parent_tab pt
where pt.col in (
select cs.col from correlated_subquery cs
where cs.col2 = pt.col2
)
with common_table_expression as (
select * from subquery
)
select * from common_table_expression
Scalar Subquery
You can use these in most places you would use a column. For example, the select or order by
clauses like so:
select t.*,
( select count(*) from scalar_subquery )
from tab t
order by ( select column from another_scalar_subquery )
These must return one column and at most one row. If a scalar subquery returns two or more rows,
you'll get an error (ORA-01427: single-row subquery returns more than one row).