> ## Documentation Index
> Fetch the complete documentation index at: /documents/llms.txt
> Use this file to discover all available pages before exploring further.

# CREATE SEMANTIC VIEW

> Create a semantic view that defines tables, relationships, facts, dimensions, and metrics for a business domain.

## 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 its `RELATIONSHIPS` 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 in `WHERE` filters and comparisons.

Additionally, view-level `AI_SQL_GENERATION` and `AI_QUESTION_CATEGORIZATION`
instructions let you provide domain context and disambiguation hints directly in
the semantic view definition.

## Syntax

```SQL theme={null}
CREATE [OR REPLACE] SEMANTIC VIEW [IF NOT EXISTS] [<db>.]<view_name>
  TABLES (
    logicalTableDef [, ...]
  )
  [RELATIONSHIPS (
    relationshipDef [, ...]
  )]
  [FACTS (
    factExpr [, ...]
  )]
  [FILTER <boolean_expression>]
  [DIMENSIONS (
    dimensionExpr [, ...]
  )]
  [METRICS (
    metricExpr [, ...]
  )]
  [COMMENT = '<view_comment>']
  [AI_SQL_GENERATION = '<sql_generation_instructions>']
  [AI_QUESTION_CATEGORIZATION = '<categorization_instructions>']
  [COPY GRANTS]
```

***

### logicalTableDef

Declares a base table and assigns it a local alias within the view.

```SQL theme={null}
[<table_alias> AS] <base_table_name>
  [PRIMARY KEY (<col> [, ...])]
  [UNIQUE (<unique_col> [, ...]) [...]]
  [CONSTRAINT [<constraint_name>] DISTINCT RANGE
     BETWEEN <start_col> AND <end_col> EXCLUSIVE]
  [WITH SYNONYMS [=] ('<synonym>' [, ...])]
  [COMMENT = '<table_comment>']
```

| Clause | Description |
| - | - |
| `table_alias` | Local alias used in relationship, fact, dimension, and metric clauses. Defaults to the bare table name. |
| `PRIMARY KEY` | Declares the primary key columns. Used for automatic key resolution in `RELATIONSHIPS`. |
| `UNIQUE` | Declares one or more unique key groups (fallback when no primary key). |
| `CONSTRAINT DISTINCT RANGE BETWEEN ... AND ... EXCLUSIVE` | Declares that rows in this table are non-overlapping ranges `[start_col, end_col)`. |
| `WITH SYNONYMS` | Alternative names users and AI may use to refer to this table (e.g. `'orders'`, `'order data'`, `'sales'`). |
| `COMMENT` | Business-level description of the table. The AI uses this to understand what the table represents. |

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

```SQL theme={null}
CREATE VIEW sales_db.v_orders AS
SELECT o_orderkey, o_custkey, o_totalprice, o_orderdate FROM sales_db.orders;

CREATE SEMANTIC VIEW sales_db.order_metrics
  TABLES (
    orders    AS sales_db.v_orders PRIMARY KEY (o_orderkey),
    customers AS sales_db.customer PRIMARY KEY (c_custkey)
  )
  RELATIONSHIPS (orders (o_custkey) REFERENCES customers)
  DIMENSIONS (orders.order_date AS o_orderdate)
  METRICS (orders.total_price AS SUM(o_totalprice));
```

Keys such as `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.

```SQL theme={null}
[<rel_name> AS]
  <from_alias> (<from_col> [, ...])
  [INNER | LEFT]
  REFERENCES <to_alias> [(<refColSpec> [, ...])]
```

The optional `INNER` or `LEFT` keyword, written between the referencing column
list and `REFERENCES`, pins the join type of this one relationship:

| Written | Effect on this relationship |
| - | - |
| `INNER` | Always joined as an inner join |
| `LEFT` | Always joined as a left outer join |
| omitted | Follows the session variable `enable_semantic_view_inner_join` |

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](/documents/4.2/sql-reference/sql-statements/semantic-view/SHOW_CREATE_SEMANTIC_VIEW.md), 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**:

| Syntax | Join type produced |
| - | - |
| `<col_name>` | Equal join: `from.col = to.col` |
| `ASOF <col_name>` | ASOF join: `from.col >= to.col` (uses `ASOF LEFT/INNER JOIN`) |
| `BETWEEN <start_col> AND <end_col> EXCLUSIVE` | Range join: `from.col >= to.start_col AND from.col < to.end_col` |

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:

1. Exactly one alias has in-degree 0. That alias is the **root**, typically the
   fact table.
2. Every other alias is reachable from the root by following relationships.

TPC-H and SSB are single snowflakes, rooted at `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:

```SQL theme={null}
-- Two fact tables sharing a dimension: two roots (sales, returns).
CREATE SEMANTIC VIEW bad_two_facts
  TABLES (
    sales   AS store_sales,
    returns AS store_returns,
    dates   AS date_dim PRIMARY KEY (d_date_sk)
  )
  RELATIONSHIPS (
    sales (ss_sold_date_sk) REFERENCES dates,
    returns (sr_returned_date_sk) REFERENCES dates
  );

-- Two tables and no relationship at all: two roots.
CREATE SEMANTIC VIEW bad_disconnected
  TABLES (
    sales AS store_sales,
    dates AS date_dim PRIMARY KEY (d_date_sk)
  );
```

Relationships that form a cycle leave no root, and a relationship from a table to
itself is rejected as well.

***

### factExpr

Declares a raw (non-aggregated) column expression exposed as a flat field for
Style-2 queries.

```SQL theme={null}
[PRIVATE | PUBLIC] <table_alias>.<name> [LABELS = (FILTER)] AS <sql_expression>
  [WITH SYNONYMS [=] ('<synonym>' [, ...])]
  [COMMENT = '<fact_comment>']
  [SAMPLE_VALUES [=] ('<value>' [, ...])]
```

| Clause | Description |
| - | - |
| `PRIVATE \| PUBLIC` | Visibility modifier. `PUBLIC` (default) means the column is exposed to external queries and AI. `PRIVATE` hides it from Style-1 queries and AI suggestions but allows internal use. |
| `LABELS = (FILTER)` | Marks this fact as a **reusable named filter**. `<sql_expression>` must be a boolean predicate; the fact can then be referenced by name in a query `WHERE` clause (e.g. `WHERE orders.fulfilled`), where it expands to the underlying predicate. |
| `WITH SYNONYMS` | Alternative names for this fact (e.g. `'line id'`, `'item identifier'`). |
| `COMMENT` | Describes what this raw value represents. |
| `SAMPLE_VALUES` | Representative example values for this fact (e.g. `'A123'`, `'B456'`). Used by AI to learn the value format. See [Sample values guide](#sample-values-guide). |

***

### dimensionExpr

Declares a grouping attribute used in aggregation queries.

```SQL theme={null}
[PUBLIC] <table_alias>.<name> [LABELS = (FILTER)] AS <sql_expression>
  [WITH SYNONYMS [=] ('<synonym>' [, ...])]
  [COMMENT = '<dimension_comment>']
  [SAMPLE_VALUES [=] ('<value>' [, ...])]
  [WITH CORTEX SEARCH SERVICE <search_service_name> [USING <search_col>]]
```

| Clause | Description |
| - | - |
| `PUBLIC` | When specified, marks this dimension as explicitly public. |
| `LABELS = (FILTER)` | Marks this dimension as a **reusable named filter**. `<sql_expression>` must be a boolean predicate; reference the dimension by name in a query `WHERE` clause (e.g. `WHERE customers.active`) and it expands to the underlying predicate. |
| `WITH SYNONYMS` | Alternative names users may say (e.g. `'region'`, `'territory'`, `'area'`). Used by AI to resolve natural-language dimension references. |
| `COMMENT` | Business meaning of this dimension (e.g. `'Calendar year of the order date'`). |
| `SAMPLE_VALUES` | Representative example values this dimension takes (e.g. `'F'`, `'O'`, `'P'`). Used by AI to generate correct literals in filters. See [Sample values guide](#sample-values-guide). |
| `WITH CORTEX SEARCH SERVICE` | Associates a full-text search service for AI-assisted lookup of dimension values. |

***

### metricExpr (regular aggregate)

Declares an aggregate expression — the primary output of Style-1 queries.

```SQL theme={null}
[PRIVATE | PUBLIC] <table_alias>.<name>
  [USING (<rel_name> [, ...])]
  [NON ADDITIVE BY (<sort_key> [, ...])]
  AS <aggregate_expression>
  [WITH SYNONYMS [=] ('<synonym>' [, ...])]
  [COMMENT = '<metric_comment>']
  [SAMPLE_VALUES [=] ('<value>' [, ...])]
```

| Clause | Description |
| - | - |
| `PRIVATE \| PUBLIC` | Visibility modifier (same semantics as for facts). |
| `USING (rel_name, ...)` | Restricts which relationship(s) are used when joining for this metric. Useful when multiple join paths exist between two tables. |
| `NON ADDITIVE BY (sort_key, ...)` | Marks the metric as non-additive over the given sort key (e.g. a point-in-time balance). Prevents incorrect cross-period aggregation. |
| `WITH SYNONYMS` | Alternative names for this metric (e.g. `'revenue'`, `'sales amount'`, `'total sales'`). |
| `COMMENT` | Describes what the metric measures and how it should be interpreted. |
| `SAMPLE_VALUES` | Representative example result values for this metric (e.g. `'1250.00'`, `'9800.50'`). Used by AI to understand the metric's scale/format. See [Sample values guide](#sample-values-guide). |

***

### metricExpr (window function)

Declares a window-function metric (running totals, moving averages, etc.).

```SQL theme={null}
[PRIVATE | PUBLIC] <table_alias>.<name> AS
  <window_function_call> OVER (
    [PARTITION BY <expr> [, ...]]
    [ORDER BY <sort_key> [, ...]]
    [<window_frame>]
  )
  [WITH SYNONYMS [=] ('<synonym>' [, ...])]
  [COMMENT = '<metric_comment>']
  [SAMPLE_VALUES [=] ('<value>' [, ...])]
```

#### 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 dimensions `Q` and declared dimensions `D`:

| Clause | Inner grain | Query dimension filters |
| - | - | - |
| `FIXED DIMENSIONS (D)` | `D` | Applied to the participating keys, after the inner aggregate |
| `INCLUDE DIMENSIONS (D)` | `Q ∪ D` | Applied before the inner aggregate |
| `EXCLUDE DIMENSIONS (D)` | `Q − D` | Applied before the inner aggregate |

The view-level `FILTER` and access policies always restrict the inner input, including `FIXED`.
For example:

```sql theme={null}
FACTS (
  customers.cust_order_cnt AS COUNT(DISTINCT orders.o_order_id)
    FIXED DIMENSIONS (customers.customer_id)
)
DIMENSIONS (customers.customer_id AS customer_id)
METRICS (
  customers.avg_orders_per_customer AS AVG(customers.cust_order_cnt),
  customers.repeat_customers AS COUNT_IF(customers.cust_order_cnt >= 2)
)
```

Without `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 in `METRICS`. 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.

```sql theme={null}
METRICS (
  orders.revenue AS SUM(amount),
  orders.running AS SUM(orders.revenue) OVER (
    PARTITION BY EXCLUDING orders.day
    ORDER BY orders.day
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW),
  orders.change AS orders.revenue - LAG(orders.revenue) OVER (
    PARTITION BY EXCLUDING orders.day ORDER BY orders.day)
)
```

`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:

| Definition | May reference |
| - | - |
| Fact | Physical columns, facts, and dimensions. Row-level facts cannot reference metrics. |
| Dimension | Physical columns, facts, and dimensions. A dimension cannot reference metrics. |
| Metric | Physical columns and facts consumed by an aggregate or window expression, plus metrics declared earlier in the `METRICS` list outside aggregate/window expressions. A metric cannot reference a dimension, itself, or a later metric. |

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 in `NON ADDITIVE BY` and `ORDER BY` clauses inside window metrics.

```SQL theme={null}
<expression> [ASC | DESC] [NULLS FIRST | NULLS LAST]
```

***

### FILTER (view-level global filter)

An optional view-level filter applied to **every** query against the semantic view. It appears
once, between the `FACTS` and `DIMENSIONS` clauses.

```SQL theme={null}
FILTER <boolean_expression>
```

* 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: with `orders.order_year AS YEAR(o_orderdate)`, `FILTER order_year = 1995`
  becomes `YEAR(o_orderdate) = 1995`. Metrics cannot be used — they are aggregates, and `FILTER`
  becomes a `WHERE` predicate.
* 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 VIEW` rejects 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 `WHERE` predicate injected into the inlined query. When a query supplies its own
  `WHERE`, the view filter is combined with it using `AND`.
* Use it to scope a view to a subset of rows (soft-deleted rows excluded, a single tenant, only
  finalized orders, etc.).

Distinguish this from `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

| Parameter | Required | Description |
| - | - | - |
| `OR REPLACE` | No | Replaces an existing semantic view with the same name. |
| `IF NOT EXISTS` | No | Suppresses an error when the view already exists. |
| `db` | No | Target database. Defaults to the current database. |
| `view_name` | Yes | Name of the semantic view. |
| `TABLES` | Yes | One or more logical table declarations. |
| `RELATIONSHIPS` | No | Join graph between the declared tables. |
| `FACTS` | No | Raw (non-aggregated) column expressions. |
| `FILTER` | No | View-level (global) boolean predicate applied to every query. `AND`-merged with the query's own `WHERE`. |
| `LABELS = (FILTER)` | No | On a fact or dimension, marks it as a reusable named filter referenced by name in `WHERE`. |
| `DIMENSIONS` | No | Grouping attributes for aggregation in Style-1 queries. |
| `METRICS` | No | Aggregate expressions that are the primary output of Style-1 queries. |
| `SAMPLE_VALUES` | No | On a fact, dimension, or metric, a list of representative example values that help the AI generate correct literals. |
| `COMMENT` | No | Free-text description of the semantic view itself. |
| `AI_SQL_GENERATION` | No | Free-text instructions that tell the AI how to generate SQL from natural language for this view. Use this to clarify domain rules, preferred join paths, or metric calculation conventions. |
| `AI_QUESTION_CATEGORIZATION` | No | Free-text instructions for categorizing user questions. Helps the AI route ambiguous questions to the right metrics or dimensions. |
| `COPY GRANTS` | No | Reserved, not supported yet. `OR REPLACE` recreates the view under a new object id without carrying its grants over, so the clause is rejected instead of silently dropping privileges. Re-grant them on the new view. |

***

## Synonyms and comments guide

### Why synonyms matter

Users rarely use exact column names in natural language. A column named
`o_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:

```SQL theme={null}
METRICS (
  orders.total_price AS SUM(o_totalprice)
    WITH SYNONYMS = ('revenue', 'sales', 'total amount', 'order value')
    COMMENT = 'Total monetary value of all orders'
)
```

### Why comments matter

Comments give the AI semantic context that column names cannot:

```SQL theme={null}
DIMENSIONS (
  orders.order_year AS YEAR(o_orderdate)
    COMMENT = 'Calendar year in which the order was placed.
               Use this when the user asks about annual or yearly trends.'
)
```

### 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'`):

```SQL theme={null}
DIMENSIONS (
  orders.order_status AS o_orderstatus
    WITH SYNONYMS = ('status', 'state')
    COMMENT = 'Order lifecycle status code.'
    SAMPLE_VALUES = ('F', 'O', 'P')          -- F = fulfilled, O = open, P = pending
)
```

With the sample values above, a question like *"how many fulfilled orders?"* can be
translated to `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')` and `SAMPLE_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
  (as `sample_values`), and the REST YAML API.

### Synonyms on tables

Table synonyms help the AI understand which table a user is talking about:

```SQL theme={null}
TABLES (
  orders AS sales_db.orders PRIMARY KEY (o_orderkey)
    WITH SYNONYMS = ('sales', 'purchases', 'order data')
    COMMENT = 'All customer orders placed in the system',
  customer AS sales_db.customer PRIMARY KEY (c_custkey)
    WITH SYNONYMS = ('client', 'buyer', 'account')
    COMMENT = 'Customer master data'
)
```

### AI\_SQL\_GENERATION instructions

Provide domain-specific rules or disambiguation hints at the view level:

```SQL theme={null}
AI_SQL_GENERATION =
  'This view covers B2B sales data.
   When the user mentions "revenue" without a time filter, default to
   the current fiscal year. When the user asks about "top customers",
   rank by orders.total_price descending.'
```

***

## Examples

### Example 1: Two-table view with synonyms and comments

**Setup**

```SQL theme={null}
DROP DATABASE IF EXISTS sales_db;
CREATE DATABASE sales_db;
USE sales_db;

CREATE TABLE orders (
  o_orderkey    BIGINT NOT NULL,
  o_custkey     BIGINT NOT NULL,
  o_orderstatus VARCHAR(1),
  o_totalprice  DOUBLE,
  o_orderdate   DATE
) ENGINE=OLAP
DISTRIBUTED BY HASH(o_orderkey)
PROPERTIES ("replication_num" = "1");

CREATE TABLE customer (
  c_custkey  BIGINT NOT NULL,
  c_name     VARCHAR(25),
  c_acctbal  DOUBLE
) ENGINE=OLAP
DISTRIBUTED BY HASH(c_custkey)
PROPERTIES ("replication_num" = "1");

INSERT INTO customer VALUES
  (1, 'Alice',   1000.0),
  (2, 'Bob',     2000.0),
  (3, 'Charlie',  500.0);

INSERT INTO orders VALUES
  (101, 1, 'O', 150.00, '2024-01-15'),
  (102, 1, 'F', 300.00, '2024-02-20'),
  (103, 2, 'O', 450.00, '2024-01-10'),
  (104, 2, 'F', 200.00, '2024-03-05'),
  (105, 3, 'O', 100.00, '2024-02-01');
```

**Create semantic view**

```SQL theme={null}
CREATE SEMANTIC VIEW sales_db.order_metrics
  TABLES (
    orders   AS sales_db.orders   PRIMARY KEY (o_orderkey)
      WITH SYNONYMS = ('sales', 'purchases')
      COMMENT = 'All customer orders',
    customer AS sales_db.customer PRIMARY KEY (c_custkey)
      WITH SYNONYMS = ('client', 'buyer', 'account')
      COMMENT = 'Customer master data'
  )
  RELATIONSHIPS (
    ord_to_cust AS orders (o_custkey) REFERENCES customer
  )
  DIMENSIONS (
    orders.order_date AS o_orderdate
      WITH SYNONYMS = ('order date', 'purchase date', 'sale date')
      COMMENT = 'Date the order was placed',
    customer.cust_name AS c_name
      WITH SYNONYMS = ('customer', 'client name', 'buyer name')
      COMMENT = 'Full name of the customer'
  )
  METRICS (
    orders.total_price AS SUM(o_totalprice)
      WITH SYNONYMS = ('revenue', 'sales', 'total sales', 'order value')
      COMMENT = 'Total monetary value of all orders',
    customer.cust_count AS COUNT(c_custkey)
      WITH SYNONYMS = ('number of customers', 'customer count', 'unique customers')
      COMMENT = 'Count of distinct customers'
  )
  COMMENT = 'Order metrics with customer info'
  AI_SQL_GENERATION =
    'Focus on aggregated order metrics.
     Default time range is the current calendar year when not specified.';
```

**Query examples**

```SQL theme={null}
-- Total revenue per customer (Style-1)
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS    orders.total_price, customer.cust_count
  DIMENSIONS customer.cust_name
)
ORDER BY cust_name;

-- Revenue for fulfilled orders only
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS    orders.total_price
  DIMENSIONS customer.cust_name
  WHERE      o_orderstatus = 'F'
)
ORDER BY cust_name;

-- Top 2 customers by revenue
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS    orders.total_price
  DIMENSIONS customer.cust_name
  LIMIT 2
)
ORDER BY cust_name;

-- Switch to INNER JOIN
SET enable_semantic_view_inner_join = true;
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS    orders.total_price
  DIMENSIONS customer.cust_name
)
ORDER BY cust_name;
SET enable_semantic_view_inner_join = false;
```

**Cleanup**

```SQL theme={null}
DROP DATABASE sales_db;
```

***

### Example 2: Three-table view with auto-resolved join keys

When the referenced table has a single primary key, the column list after
`REFERENCES` can be omitted.

**Setup**

```SQL theme={null}
DROP DATABASE IF EXISTS sales_db;
CREATE DATABASE sales_db;
USE sales_db;

CREATE TABLE orders (
  o_orderkey    BIGINT NOT NULL,
  o_custkey     BIGINT NOT NULL,
  o_orderstatus VARCHAR(1),
  o_totalprice  DOUBLE,
  o_orderdate   DATE
) ENGINE=OLAP
DISTRIBUTED BY HASH(o_orderkey)
PROPERTIES ("replication_num" = "1");

CREATE TABLE customer (
  c_custkey  BIGINT NOT NULL,
  c_name     VARCHAR(25),
  c_acctbal  DOUBLE
) ENGINE=OLAP
DISTRIBUTED BY HASH(c_custkey)
PROPERTIES ("replication_num" = "1");

CREATE TABLE lineitem (
  l_orderkey      BIGINT NOT NULL,
  l_linenumber    INT NOT NULL,
  l_quantity      DOUBLE,
  l_discount      DOUBLE,
  l_extendedprice DOUBLE
) ENGINE=OLAP
DISTRIBUTED BY HASH(l_orderkey)
PROPERTIES ("replication_num" = "1");

INSERT INTO customer VALUES
  (1, 'Alice',   1000.0),
  (2, 'Bob',     2000.0),
  (3, 'Charlie',  500.0);

INSERT INTO orders VALUES
  (101, 1, 'O', 150.00, '2024-01-15'),
  (102, 1, 'F', 300.00, '2024-02-20'),
  (103, 2, 'O', 450.00, '2024-01-10'),
  (104, 2, 'F', 200.00, '2024-03-05'),
  (105, 3, 'O', 100.00, '2024-02-01');

INSERT INTO lineitem VALUES
  (101, 1,  5.0, 0.05, 475.00),
  (101, 2,  3.0, 0.00, 300.00),
  (102, 1, 10.0, 0.10, 900.00),
  (103, 1,  2.0, 0.00, 200.00),
  (104, 1,  7.0, 0.05, 665.00),
  (105, 1,  1.0, 0.00, 100.00);
```

**Create semantic view**

```SQL theme={null}
CREATE SEMANTIC VIEW sales_db.revenue_analysis
  TABLES (
    orders     AS sales_db.orders     PRIMARY KEY (o_orderkey)
      WITH SYNONYMS = ('sales', 'order data')
      COMMENT = 'Customer orders',
    customers  AS sales_db.customer   PRIMARY KEY (c_custkey)
      WITH SYNONYMS = ('clients', 'buyers', 'accounts')
      COMMENT = 'Customer master data',
    line_items AS sales_db.lineitem   PRIMARY KEY (l_orderkey, l_linenumber)
      WITH SYNONYMS = ('items', 'order lines', 'line item data')
      COMMENT = 'Individual line items within each order'
  )
  RELATIONSHIPS (
    orders_to_customers AS orders (o_custkey) REFERENCES customers,
    line_item_to_orders AS line_items (l_orderkey) REFERENCES orders
  )
  FACTS (
    line_items.line_item_id AS CONCAT(l_orderkey, '-', l_linenumber)
      WITH SYNONYMS = ('item id', 'line id')
      COMMENT = 'Unique identifier for each order line item'
  )
  DIMENSIONS (
    customers.customer_name AS c_name
      WITH SYNONYMS = ('customer', 'client name', 'buyer')
      COMMENT = 'Name of the customer',
    orders.order_date AS o_orderdate
      WITH SYNONYMS = ('order date', 'purchase date')
      COMMENT = 'Date when the order was placed',
    orders.order_year AS YEAR(o_orderdate)
      WITH SYNONYMS = ('year', 'order year', 'sales year')
      COMMENT = 'Calendar year of the order. Use for annual trend analysis.'
  )
  METRICS (
    customers.customer_count AS COUNT(c_custkey)
      WITH SYNONYMS = ('number of customers', 'unique customers', 'customer count')
      COMMENT = 'Count of distinct customers',
    orders.avg_order_value AS AVG(o_totalprice)
      WITH SYNONYMS = ('average order', 'avg order size', 'mean order value')
      COMMENT = 'Average monetary value per order'
  )
  COMMENT = 'Revenue analysis semantic view'
  AI_SQL_GENERATION =
    'When the user asks about trends, group by order_year.
     When the user asks about top customers, rank by customer_count descending.';
```

**Query examples**

```SQL theme={null}
-- Average order value per customer
SELECT * FROM SEMANTIC_VIEW(
  sales_db.revenue_analysis
  METRICS    orders.avg_order_value
  DIMENSIONS customers.customer_name
)
ORDER BY customer_name;

-- Customer count and average order value by year
SELECT * FROM SEMANTIC_VIEW(
  sales_db.revenue_analysis
  DIMENSIONS orders.order_year, customers.customer_name
  METRICS    customers.customer_count, orders.avg_order_value
)
ORDER BY order_year, customer_name;
```

**Cleanup**

```SQL theme={null}
DROP DATABASE sales_db;
```

***

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

**Setup**

```SQL theme={null}
DROP DATABASE IF EXISTS trading_db;
CREATE DATABASE trading_db;
USE trading_db;

-- Trades: individual transactions
CREATE TABLE Trades (
  trade_id   BIGINT NOT NULL,
  product_id VARCHAR(20),
  trade_time DATETIME,
  amount     DOUBLE
) ENGINE=OLAP
DISTRIBUTED BY HASH(trade_id)
PROPERTIES ("replication_num" = "1");

-- Prices: point-in-time price snapshots (ASOF join target)
CREATE TABLE Prices (
  product_id VARCHAR(20),
  price_time DATETIME,
  price      DOUBLE
) ENGINE=OLAP
DUPLICATE KEY (product_id, price_time)
DISTRIBUTED BY HASH(product_id)
PROPERTIES ("replication_num" = "1");

INSERT INTO Prices VALUES
  ('P1', '2024-01-01 08:00:00', 10.0),
  ('P1', '2024-01-01 12:00:00', 11.0),
  ('P1', '2024-01-02 09:00:00', 12.0),
  ('P2', '2024-01-01 09:00:00', 20.0),
  ('P2', '2024-01-01 15:00:00', 21.0);

INSERT INTO Trades VALUES
  (1, 'P1', '2024-01-01 10:00:00', 100.0),
  (2, 'P1', '2024-01-01 14:00:00', 200.0),
  (3, 'P1', '2024-01-02 10:00:00', 150.0),
  (4, 'P2', '2024-01-01 11:00:00', 300.0),
  (5, 'P2', '2024-01-01 18:00:00', 250.0);
```

**Create semantic view**

```SQL theme={null}
CREATE SEMANTIC VIEW trading_db.product_sales_analysis
  TABLES (
    trades AS trading_db.Trades PRIMARY KEY (trade_id)
      WITH SYNONYMS = ('transactions', 'sales events')
      COMMENT = 'Individual trade transactions',
    prices AS trading_db.Prices PRIMARY KEY (product_id, price_time)
      WITH SYNONYMS = ('price history', 'price table')
      COMMENT = 'Historical prices keyed by product and effective timestamp'
  )
  RELATIONSHIPS (
    -- Match each trade to the most recent price at or before trade_time
    trades (product_id, trade_time)
      REFERENCES prices (product_id, ASOF price_time)
  )
  DIMENSIONS (
    trades.product_id AS product_id
      WITH SYNONYMS = ('product', 'item', 'SKU')
      COMMENT = 'Identifier of the traded product',
    trades.trade_time AS trade_time
      WITH SYNONYMS = ('trade date', 'transaction time', 'when traded')
      COMMENT = 'Timestamp of the trade'
  )
  METRICS (
    trades.total_revenue AS SUM(trades.amount * prices.price)
      WITH SYNONYMS = ('revenue', 'sales revenue', 'income')
      COMMENT = 'Total revenue computed using the point-in-time price at trade time',
    trades.total_quantity AS SUM(trades.amount)
      WITH SYNONYMS = ('volume', 'quantity sold', 'units traded')
      COMMENT = 'Total number of units traded'
  )
  COMMENT = 'Point-in-time revenue using ASOF price matching'
  AI_SQL_GENERATION =
    'Always use point-in-time pricing. Do not aggregate prices independently.';
```

The ASOF relationship generates:

```SQL theme={null}
FROM trading_db.Trades AS trades
ASOF LEFT JOIN trading_db.Prices AS prices
  ON trades.product_id = prices.product_id
 AND trades.trade_time >= prices.price_time
```

**Query examples**

```SQL theme={null}
-- Total revenue and quantity per product
SELECT * FROM SEMANTIC_VIEW(
  trading_db.product_sales_analysis
  METRICS    trades.total_revenue, trades.total_quantity
  DIMENSIONS trades.product_id
)
ORDER BY product_id;

-- Revenue filtered to products exceeding 3000
SELECT * FROM SEMANTIC_VIEW(
  trading_db.product_sales_analysis
  METRICS    trades.total_revenue
  DIMENSIONS trades.product_id
  HAVING     trades.total_revenue > 3000
)
ORDER BY product_id;
```

**Cleanup**

```SQL theme={null}
DROP DATABASE trading_db;
```

***

### Example 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**

```SQL theme={null}
DROP DATABASE IF EXISTS trading_range_db;
CREATE DATABASE trading_range_db;
USE trading_range_db;

-- Trades fact table
CREATE TABLE Trades (
  trade_id   BIGINT NOT NULL,
  product_id VARCHAR(20),
  trade_time DATETIME,
  amount     DOUBLE
) ENGINE=OLAP
DISTRIBUTED BY HASH(trade_id)
PROPERTIES ("replication_num" = "1");

-- Prices with validity intervals [price_start_time, price_end_time)
CREATE TABLE Prices (
  product_id       VARCHAR(20),
  price_start_time DATETIME,
  price_end_time   DATETIME,
  price            DOUBLE
) ENGINE=OLAP
DUPLICATE KEY (product_id, price_start_time)
DISTRIBUTED BY HASH(product_id)
PROPERTIES ("replication_num" = "1");

INSERT INTO Prices VALUES
  ('P1', '2024-01-01 00:00:00', '2024-01-01 12:00:00', 10.0),
  ('P1', '2024-01-01 12:00:00', '2024-01-02 00:00:00', 11.0),
  ('P1', '2024-01-02 00:00:00', '2024-01-03 00:00:00', 12.0),
  ('P2', '2024-01-01 00:00:00', '2024-01-01 15:00:00', 20.0),
  ('P2', '2024-01-01 15:00:00', '2024-01-02 00:00:00', 21.0);

INSERT INTO Trades VALUES
  (1, 'P1', '2024-01-01 10:00:00', 100.0),
  (2, 'P1', '2024-01-01 14:00:00', 200.0),
  (3, 'P1', '2024-01-02 10:00:00', 150.0),
  (4, 'P2', '2024-01-01 11:00:00', 300.0),
  (5, 'P2', '2024-01-01 18:00:00', 250.0);
```

**Create semantic view**

```SQL theme={null}
CREATE SEMANTIC VIEW trading_range_db.product_sales_range
  TABLES (
    trades AS trading_range_db.Trades PRIMARY KEY (trade_id)
      WITH SYNONYMS = ('transactions', 'sales events')
      COMMENT = 'Individual trade transactions',
    prices AS trading_range_db.Prices PRIMARY KEY (product_id, price_start_time)
      WITH SYNONYMS = ('price intervals', 'validity periods')
      COMMENT = 'Prices valid during [price_start_time, price_end_time)'
  )
  RELATIONSHIPS (
    -- Match each trade to the price valid during [price_start_time, price_end_time)
    trades (product_id, trade_time)
      REFERENCES prices (product_id, BETWEEN price_start_time AND price_end_time EXCLUSIVE)
  )
  DIMENSIONS (
    trades.product_id AS product_id
      WITH SYNONYMS = ('product', 'item', 'SKU')
      COMMENT = 'Product identifier',
    trades.trade_time AS trade_time
      WITH SYNONYMS = ('trade date', 'transaction time')
      COMMENT = 'Timestamp of the trade'
  )
  METRICS (
    trades.total_revenue AS SUM(trades.amount * prices.price)
      WITH SYNONYMS = ('revenue', 'sales revenue')
      COMMENT = 'Revenue using the price valid at trade time',
    trades.total_quantity AS SUM(trades.amount)
      WITH SYNONYMS = ('volume', 'units traded')
      COMMENT = 'Total units traded'
  )
  COMMENT = 'Revenue using BETWEEN range price matching';
```

The BETWEEN relationship generates:

```SQL theme={null}
FROM trading_range_db.Trades AS trades
LEFT JOIN trading_range_db.Prices AS prices
  ON trades.product_id = prices.product_id
 AND trades.trade_time >= prices.price_start_time
 AND trades.trade_time < prices.price_end_time
```

**Query examples**

```SQL theme={null}
-- Total revenue and quantity per product
SELECT * FROM SEMANTIC_VIEW(
  trading_range_db.product_sales_range
  METRICS    trades.total_revenue, trades.total_quantity
  DIMENSIONS trades.product_id
)
ORDER BY product_id;

-- Revenue per product and trade timestamp
SELECT * FROM SEMANTIC_VIEW(
  trading_range_db.product_sales_range
  METRICS    trades.total_revenue
  DIMENSIONS trades.product_id, trades.trade_time
)
ORDER BY product_id, trade_time;
```

**Cleanup**

```SQL theme={null}
DROP DATABASE trading_range_db;
```

***

### Example 5: Non-additive metric and access modifiers

Use `NON 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**

```SQL theme={null}
DROP DATABASE IF EXISTS finance_db;
CREATE DATABASE finance_db;
USE finance_db;

CREATE TABLE daily_balance (
  account_id     VARCHAR(20) NOT NULL,
  snapshot_date  DATE        NOT NULL,
  balance_amount DOUBLE
) ENGINE=OLAP
DISTRIBUTED BY HASH(account_id)
PROPERTIES ("replication_num" = "1");

INSERT INTO daily_balance VALUES
  ('A001', '2024-01-01', 10000.0),
  ('A001', '2024-01-02', 10500.0),
  ('A001', '2024-01-03',  9800.0),
  ('A002', '2024-01-01', 25000.0),
  ('A002', '2024-01-02', 24500.0),
  ('A002', '2024-01-03', 26000.0);
```

**Create semantic view**

```SQL theme={null}
CREATE SEMANTIC VIEW finance_db.account_balances
  TABLES (
    snapshots AS finance_db.daily_balance PRIMARY KEY (account_id, snapshot_date)
      WITH SYNONYMS = ('balances', 'daily balances')
      COMMENT = 'Daily end-of-day balance snapshots per account'
  )
  DIMENSIONS (
    snapshots.account_id AS account_id
      WITH SYNONYMS = ('account', 'account number')
      COMMENT = 'Account identifier',
    snapshots.snapshot_date AS snapshot_date
      WITH SYNONYMS = ('date', 'balance date', 'as of date')
      COMMENT = 'Date of the balance snapshot'
  )
  METRICS (
    -- Non-additive: the balance at a point in time cannot be summed across dates
    snapshots.end_of_day_balance AS SUM(balance_amount)
      NON ADDITIVE BY (snapshot_date DESC)
      WITH SYNONYMS = ('balance', 'account balance', 'closing balance')
      COMMENT = 'End-of-day account balance.
                 Non-additive over time: use the latest snapshot date per account.',

    -- Private helper used in calculations but not surfaced to AI or external queries
    PRIVATE snapshots.raw_balance_sum AS SUM(balance_amount)
      COMMENT = 'Internal: unconstrained sum, do not expose directly'
  )
  COMMENT = 'Account balance analytics'
  AI_SQL_GENERATION =
    'When the user asks for "current balance" or "latest balance",
     filter to MAX(snapshot_date) per account.
     Never sum end_of_day_balance across multiple dates.';
```

**Query examples**

```SQL theme={null}
-- Balance per account per date
SELECT * FROM SEMANTIC_VIEW(
  finance_db.account_balances
  METRICS    snapshots.end_of_day_balance
  DIMENSIONS snapshots.account_id, snapshots.snapshot_date
)
ORDER BY account_id, snapshot_date;

-- Latest balance per account
SELECT * FROM SEMANTIC_VIEW(
  finance_db.account_balances
  METRICS    snapshots.end_of_day_balance
  DIMENSIONS snapshots.account_id
  WHERE      snapshot_date = (SELECT MAX(snapshot_date) FROM finance_db.daily_balance)
)
ORDER BY account_id;
```

**Cleanup**

```SQL theme={null}
DROP DATABASE finance_db;
```

***

### Example 6: Window function metric

**Setup**

```SQL theme={null}
DROP DATABASE IF EXISTS sales_db;
CREATE DATABASE sales_db;
USE sales_db;

CREATE TABLE orders (
  o_orderkey    BIGINT NOT NULL,
  o_custkey     BIGINT NOT NULL,
  o_orderstatus VARCHAR(1),
  o_totalprice  DOUBLE,
  o_orderdate   DATE
) ENGINE=OLAP
DISTRIBUTED BY HASH(o_orderkey)
PROPERTIES ("replication_num" = "1");

INSERT INTO orders VALUES
  (101, 1, 'O', 150.00, '2024-01-15'),
  (102, 1, 'F', 300.00, '2024-02-20'),
  (103, 2, 'O', 450.00, '2024-01-10'),
  (104, 2, 'F', 200.00, '2024-03-05'),
  (105, 3, 'O', 100.00, '2024-02-01');
```

**Create semantic view**

```SQL theme={null}
CREATE SEMANTIC VIEW sales_db.running_totals
  TABLES (
    orders AS sales_db.orders PRIMARY KEY (o_orderkey)
      WITH SYNONYMS = ('sales', 'transactions')
      COMMENT = 'Customer orders'
  )
  DIMENSIONS (
    orders.order_date AS o_orderdate
      WITH SYNONYMS = ('date', 'sale date')
      COMMENT = 'Date the order was placed'
  )
  METRICS (
    orders.daily_revenue AS SUM(o_totalprice)
      WITH SYNONYMS = ('daily sales', 'revenue per day')
      COMMENT = 'Total revenue for each order date',

    orders.running_revenue AS SUM(o_totalprice) OVER (
      ORDER BY o_orderdate ASC
      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    )
      WITH SYNONYMS = ('cumulative revenue', 'running total', 'year-to-date revenue')
      COMMENT = 'Cumulative revenue ordered by date'
  )
  COMMENT = 'Daily and cumulative revenue';
```

**Query examples**

> **Note:** A single SEMANTIC\_VIEW query must request only window metrics or only aggregation
> metrics — mixing both in the same METRICS clause is not allowed.

```SQL theme={null}
-- Daily revenue by date (aggregation metric only)
SELECT * FROM SEMANTIC_VIEW(
  sales_db.running_totals
  METRICS    orders.daily_revenue
  DIMENSIONS orders.order_date
)
ORDER BY order_date;

-- Running total by date (window metric only — dimensions are output directly, no GROUP BY)
SELECT * FROM SEMANTIC_VIEW(
  sales_db.running_totals
  METRICS    orders.running_revenue
  DIMENSIONS orders.order_date
)
ORDER BY order_date LIMIT 10;

-- Running total without explicit dimensions
SELECT * FROM SEMANTIC_VIEW(
  sales_db.running_totals
  METRICS    orders.running_revenue
)
LIMIT 10;
```

**Cleanup**

```SQL theme={null}
DROP DATABASE sales_db;
```

***

## Notes on join type

By default the database uses `LEFT 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`:

```SQL theme={null}
SET enable_semantic_view_inner_join = true;
SELECT * FROM SEMANTIC_VIEW(sales_db.order_metrics METRICS orders.total_price);
SET enable_semantic_view_inner_join = false;
```

***

## See also

* [DROP SEMANTIC VIEW](/documents/4.2/sql-reference/sql-statements/semantic-view/DROP_SEMANTIC_VIEW.md)
* [SHOW SEMANTIC VIEWS](/documents/4.2/sql-reference/sql-statements/semantic-view/SHOW_SEMANTIC_VIEWS.md)
* [SHOW CREATE SEMANTIC VIEW](/documents/4.2/sql-reference/sql-statements/semantic-view/SHOW_CREATE_SEMANTIC_VIEW.md)
* [Semantic views](/documents/4.2/using_starrocks/semantic_view.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.