You are on page 1of 3

SUBQUERIES BY Narayana Reddy

Summary

Oracle Database supports many different types of subquery. These include:

 Inline views
 Nested views
 Subquery factoring aka common table expressions or the with clause.
 Scalar subqueries

Background

Oracle Database supports the following types of subquery:

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

An uncorrelated subquery has no join to the parent table within it:

select *
from parent_tab pt
where pt.col in (
select us.col from uncorrelated_subquery us
)

Correlated Subquery

A correlated subquery does join to the parent table.

select *
from parent_tab pt
where pt.col in (
select cs.col from correlated_subquery cs
where cs.col2 = pt.col2
)

Subquery Factoring aka Common Table Expressions


Common table expressions go in the with clause of select statements. This allows you to name
subqueries and refer to them in the from clause of following selects. 

It goes at the top of your select statement, for example:

with common_table_expression as (
select * from subquery
)
select * from common_table_expression

The database processes the with clause from top to bottom. 

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).

You might also like