Description
Creates a semantic view — a logical abstraction over physical tables that defines tables, relationships, facts, dimensions, and metrics in a business domain. A semantic view carries no physical storage of its own. When queried it is transparently inlined into the surrounding SQL as a derived subquery, using the join topology described in itsRELATIONSHIPS clause.
Synonyms and comments are the primary mechanism for AI-assisted SQL generation.
Each element of a semantic view can carry:
COMMENT— a free-text description that explains what the element represents in business terms. The AI uses comments to map natural-language phrases to the correct columns or metrics.WITH SYNONYMS— alternative names that users commonly use to refer to the element. The AI uses synonyms to handle paraphrases, abbreviations, and domain-specific jargon.SAMPLE_VALUES— a handful of representative example values for a fact, dimension, or metric. The AI uses them to learn the column’s value format (e.g.'F'/'O'status codes,'2023-01-01'dates) so it can generate correct literals inWHEREfilters and comparisons.
AI_SQL_GENERATION and AI_QUESTION_CATEGORIZATION
instructions let you provide domain context and disambiguation hints directly in
the semantic view definition.
Syntax
logicalTableDef
Declares a base table and assigns it a local alias within the view.What a base table may be
base_table_name may name a table, a logical view, or a materialized view — anything
with a column list for the FACTS / DIMENSIONS / METRICS expressions to resolve
against. A view may live in a different database than the semantic view, may already
aggregate, and may itself be defined over another semantic view.
PRIMARY KEY are declarations about the data, not constraints the base
object enforces, so they are declared on a view exactly as on a table.
A semantic view cannot be a base table of another semantic view: it has no column
list of its own — its output columns exist only once a query inlines it — so
CREATE SEMANTIC VIEW rejects it. Expose it through a logical view first and use that
view as the base table.
relationshipDef
Defines a join edge between two declared tables.INNER or LEFT keyword, written between the referencing column
list and REFERENCES, pins the join type of this one relationship:
A pinned join type is stored with the relationship, so it is unaffected by the
session that runs the query, it is echoed by
SHOW CREATE SEMANTIC VIEW, and it round-trips
through the YAML API as the
join_type field (see the Semantic View YAML REST
API page under sql-reference). Because the keyword
belongs to the relationship rather than to the view, one view can pin INNER on
a mandatory dimension and LEFT on an optional one.
refColSpec is one of:
A single
relationshipDef may mix multiple equal-join columns with at most
one ASOF or BETWEEN column. ASOF and BETWEEN cannot coexist in the same
relationship.
When the (<refColSpec> ...) list is omitted the referenced table must have
exactly one primary or unique key; those key columns are used automatically.
Single snowflake requirement
TABLES and RELATIONSHIPS together must form a single snowflake. Read the
declaration as a directed graph — one vertex per table alias, one edge from the
referencing table to the referenced table — and it must satisfy both of:
- Exactly one alias has in-degree 0. That alias is the root, typically the fact table.
- Every other alias is reachable from the root by following relationships.
lineitem and lineorder.
TPC-DS is not: store_sales, store_returns, catalog_sales,
catalog_returns, web_sales and web_returns are six roots that merely share
the dimension tables, so the declaration would be six overlapping snowflakes.
CREATE SEMANTIC VIEW rejects anything else. A query is free to combine a metric
from one part of the view with a dimension from another; if those two parts sit in
different snowflakes there is no primary/foreign key path between them, so no
correct join exists and the answer would be a cross product or an error at query
time instead of at CREATE time. Model one semantic view per snowflake — for
TPC-DS, one view per sales/returns channel.
The following declarations are rejected:
factExpr
Declares a raw (non-aggregated) column expression exposed as a flat field for Style-2 queries.dimensionExpr
Declares a grouping attribute used in aggregation queries.metricExpr (regular aggregate)
Declares an aggregate expression — the primary output of Style-1 queries.metricExpr (window function)
Declares a window-function metric (running totals, moving averages, etc.).Level-of-detail expressions
An LOD expression declares the grain of an inner aggregate. A metric then aggregates those inner results once at the query grain. For query dimensionsQ and declared dimensions D:
The view-level
FILTER and access policies always restrict the inner input, including FIXED.
For example:
customer_id in the query dimensions, the average counts each participating customer
once. With other dimensions, each customer contributes once to each group they participate in.
Normal metrics are computed independently at the query grain and can be selected alongside LOD metrics.
FIXED facts and scalar dimensions can also be used in detail queries and query filters.
INCLUDE and EXCLUDE facts can only be consumed by an outer metric aggregate. All LOD grain
entries must name declared, non-LOD dimensions; an empty list is allowed only for FIXED.
Parenthesize an inline LOD before combining it with scalar operations, for example
COUNT_IF((COUNT(*) FIXED DIMENSIONS (customers.customer_id)) >= 2).
Nested LODs, multiple LODs inside one outer aggregate, additional aggregation layers, and
combining LOD with window metrics are unsupported. LOD values inside an aggregate may be
combined with constants, but not with detail columns. LOD expressions cannot define the view-level FILTER.
Post-aggregation window metrics
A window may consume an aggregate metric declared earlier inMETRICS. The query first groups
by all requested dimensions, then evaluates the window over those grouped rows. Such metrics may
be queried together with ordinary aggregate and derived metrics. Window calls may participate in
scalar arithmetic, as in orders.change below. The model must declare orders.day as a dimension.
PARTITION BY EXCLUDING uses the query dimensions minus the listed dimensions. Explicit
PARTITION BY uses exactly the listed dimensions. The query must include every dimension used
in the partition, exclusion list, or window ordering; ordering may also reference an earlier
aggregate metric. WHERE filters input rows before grouping; HAVING filters the window results;
query ordering and LIMIT follow that filtering. A missing dimension produces an error naming it.
A window cannot consume another window metric or contain a nested aggregate/window call.
Physical-column windows retain their existing detail-row semantics and cannot mix with aggregate
metrics. Post-aggregation windows cannot be requested through a FACTS detail query.
SR YAML and REST exports include required_dimensions. OSI 0.1.1 exports place these metrics in
the versioned STARROCKS extension, with nonportable_metrics listing the affected metrics.
Reimporting into the database restores their definitions; other tools do not execute that extension.
Expression reference rules
References inside fact, dimension, and metric expressions follow this matrix:
Facts and dimensions may reference each other using
alias.name, regardless of declaration
order. References are expanded recursively with parentheses. Cycles are rejected at creation
with the participating object names. Cross-table row references must follow a many-to-one
relationship; table pruning follows the complete dependency chain.
If alias.name matches both a physical column and a row definition, the physical column wins
and creation emits a warning. Bare names within row definitions refer only to physical columns
of their owning table. Objects declared without a table prefix retain their existing global-name
references. Existing persisted views retain their original binding rules. SR YAML
keeps the named references. OSI export expands fields to physical expressions and retains the
original expressions in STARROCKS extensions for reimport.
Query-side semantic field names continue to select and filter the declared fields.
Metric declaration order is significant. Declare a base metric before any
derived metric that uses it. A physical column or fact in a metric must occur inside an
aggregate function, a window-function argument, or its OVER clause. Because an earlier
metric is already aggregated, it can be used in non-aggregate scalar arithmetic such as
total / count, but cannot be passed to another aggregate expression. The post-aggregation window metrics
described above are the exception for window arguments and dimension references. Within
one table alias, facts, dimensions, and metrics share one name namespace and cannot have
duplicate names. Every qualified expression reference must use an alias declared in
TABLES. These rules apply to qualified and unqualified column references and are checked
when the semantic view is created.
sort_key
Used inNON ADDITIVE BY and ORDER BY clauses inside window metrics.
FILTER (view-level global filter)
An optional view-level filter applied to every query against the semantic view. It appears once, between theFACTS and DIMENSIONS clauses.
- The expression is a boolean predicate that may reference base-table columns, facts and
dimensions, qualified (
orders.order_date) or not (o_orderstatus). Facts and dimensions are replaced by their base-table expressions when the view is inlined, so a filter on a derived dimension works: withorders.order_year AS YEAR(o_orderdate),FILTER order_year = 1995becomesYEAR(o_orderdate) = 1995. Metrics cannot be used — they are aggregates, andFILTERbecomes aWHEREpredicate. - A name that is both a declared fact/dimension and a base-table column resolves to the declared
one. An unqualified name must identify exactly one fact, dimension, or base-table column;
qualify it with a table alias when several tables declare it.
CREATE SEMANTIC VIEWrejects a reference that resolves to nothing or to more than one thing, rather than letting every query against the view fail later. - It behaves as a
WHEREpredicate injected into the inlined query. When a query supplies its ownWHERE, the view filter is combined with it usingAND. - Use it to scope a view to a subset of rows (soft-deleted rows excluded, a single tenant, only finalized orders, etc.).
LABELS = (FILTER) on a fact/dimension: the global FILTER is always
applied, whereas a filter label is a named, optional predicate the caller opts into by
referencing it in WHERE.
A query that restates a conjunct of the filter in its own WHERE does not get that predicate
applied twice: repeated top-level AND conjuncts are dropped from the inlined WHERE. This
matters for generated SQL, which often restates the model’s global filter. Conjuncts the query
does not restate are still applied.
Parameters
Synonyms and comments guide
Why synonyms matter
Users rarely use exact column names in natural language. A column namedo_totalprice might be referred to as “revenue”, “sales”, “total amount”, or
“order value”. Adding these as synonyms lets the AI match user intent to the
correct metric without fragile heuristics:
Why comments matter
Comments give the AI semantic context that column names cannot:Sample values guide
SAMPLE_VALUES attaches a few representative example values to a fact, dimension,
or metric. While synonyms and comments help the AI pick the right column, sample
values help it produce the right literal — the AI often cannot guess a column’s
value format from its name alone.
They are especially valuable for coded or enumerated columns, where the stored value
differs from how users phrase it (a user says “fulfilled orders” but the column stores
'F'):
WHERE o_orderstatus = 'F' instead of an incorrect
WHERE o_orderstatus = 'fulfilled'.
Guidelines:
- Applies to facts, dimensions, and metrics.
- Values are always string literals, regardless of the column’s real data type —
quote dates, numbers, and codes alike:
SAMPLE_VALUES = ('2023-01-01', '2024-01-01'). - Provide a small, representative set (typically 3–8 values), not the full domain.
- The
=sign is optional:SAMPLE_VALUES ('F', 'O')andSAMPLE_VALUES = ('F', 'O')are equivalent. - Sample values are metadata hints only; they do not filter or constrain query results in any way.
- They round-trip through
SHOW CREATE SEMANTIC VIEW, the SR/OSI YAML export (assample_values), and the REST YAML API.
Synonyms on tables
Table synonyms help the AI understand which table a user is talking about:AI_SQL_GENERATION instructions
Provide domain-specific rules or disambiguation hints at the view level:Examples
Example 1: Two-table view with synonyms and comments
SetupExample 2: Three-table view with auto-resolved join keys
When the referenced table has a single primary key, the column list afterREFERENCES can be omitted.
Setup
Example 3: ASOF join — point-in-time price lookup
An ASOF join matches each trade row to the most recent price snapshot at or before the trade timestamp. SetupExample 4: BETWEEN range join — price validity intervals
A BETWEEN range join matches each trade row to the price record whose validity interval[price_start_time, price_end_time) contains the trade timestamp.
Setup
Example 5: Non-additive metric and access modifiers
UseNON ADDITIVE BY to prevent incorrect summation of a point-in-time balance,
and PRIVATE to hide intermediate metrics from external queries and AI suggestions.
Setup
Example 6: Window function metric
SetupNote: A single SEMANTIC_VIEW query must request only window metrics or only aggregation metrics — mixing both in the same METRICS clause is not allowed.
Notes on join type
By default the database usesLEFT JOIN (and ASOF LEFT JOIN) when inlining a
semantic view. Set the session variable enable_semantic_view_inner_join = true
to switch to INNER JOIN / ASOF INNER JOIN: