4. Understanding the Elements of SQL Statements : Subqueries : Subqueries in the FROM Clause (Derived Tables)
 
Share this page                  
Subqueries in the FROM Clause (Derived Tables)
Derived tables let you create or simplify complex queries. Useful in data warehousing applications, they provide a way to isolate complex portions of query syntax from the rest of a query.
A derived table is the coding of a SELECT in the FROM clause of a SELECT statement. The derived table must always use a correlation name.
For example:
SELECT relid, x.attname
FROM (SELECT attrelid, attrelidx, attname,
    attfrml FROM iiattribute) x, iirelation
WHERE reltid = attrelid AND reltidx = x.attrelidx
The derived table behaves like an inline view; the rows of the result set of the derived table are read and joined to the rest of the query. If possible, the derived table is flattened into the containing query to permit the query compiler to better optimize the query as a whole.
Some complex queries cannot be implemented without using either pre-defined views or derived tables. The derived table approach is more concise than pre-defined views, and avoids having to define persistent objects, such as views, that may be used for a single query only.
For example, consider a query that joins information to some aggregate expressions. Derived tables allow the aggregates to be defined and joined to non-aggregated rows of some other tables all in the same query. Without derived tables, a persistent view would have to be defined to compute the aggregates. Then a query would have to be coded to join the aggregate view to the non-aggregated data.