6.6. In-Line Text Expansion

Another approach is to store the text of the CREATE VIEW statement and work it into the parse tree of the SELECT, INSERT, UPDATE, or DELETE statements that use it. This allows the optimizer to blend the VIEW definition into the final query plan. For example, you can create a VIEW based on a particular department, thus:

CREATE VIEW SalesDept (dept_name, city_name, ...)
AS SELECT 'Sales', city_name, ...
     FROM Departments
    WHERE dept_name = 'Sales';

and then use it as a query thus:

SELECT *
   FROM SalesDept
 WHERE city_name = 'New York';

The parser expands the VIEW into text (or an intermediate tokenized form) within the FROM clause. The query would become, in effect,

SELECT * FROM (SELECT 'Sales', city_name, ... FROM Departments ...

Get Joe Celko's Thinking in Sets: Auxiliary, Temporal, and Virtual Tables in SQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.