WITH (Common Table Expression)
Syntax
WITH
with_name AS (select_statement)
[, ...]
select_statement;Description
The WITH clause is used for defining named subqueries that can be used as a common expression in other SELECT statements. These common expressions are referred to as Common Table Expressions (CTEs), and present a temporary view of the data that is projected from its select_statement. As a result, CTEs modularize queries, making them more maintainable and versatile than subqueries.
The result of a CTE is effectively a DeltaStream Object that can be used just like any other relation defined with a DDL or subquery, and by definition takes precedence over other relations defined using a DDL.
Arguments
with_name
A name for the select_statement that defines the CTE.
select_statement
See SELECT.
Examples
Using CTEs from other CTEs
CTEs are just like any other relations, and they can be used within the SELECT statement of other CTEs. In this example, c1 projects the viewtime of each pageid from pageviews, and c2 adds a processing time to the result of that before eventually projecting proc_time, pageid and viewtime in the main SELECT statement:
Joining a Stream CTE with a Changelog CTE
Each CTE represts a local Relation meaning that their grouping/aggregation or project reflects how they present the underlying data to the query that they're part of.
In the following example, c1 represents a Stream over pageviews where Page_6 has been visited by a user, and c2 represents a Changelog over users where its grouping the changes by the userid column. When joining these two CTEs, the JOIN operation treats this as a Stream-Changelog join, and doesn't require a WITHIN window for the join criteria:
Self-joining CTEs
In this example, a single CTE is written to reshape the pageviews stream, but used twice in the JOIN operation to self-join for the resulting expanded data. The result of the joined data can be used as projected by the CTE's SELECT statement — htat is, user ID as an integer:
Create a new stream from MATCH_RECOGNIZEd CTE
This example shows a real-world query pattern matching over bus trip updates (redefined with CTEs from our Analyzing NYC Bus Data blog). A local bus trip updates relation as defined in the trip_updates CTE, which is then used in the MATCH_RECOGNIZE update to find each vehicles average time at each stop:
Last updated

