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

# Querying Semantic Views

> Query a semantic view with the SEMANTIC_VIEW() relation function or as a plain table reference.

A semantic view can be referenced in two ways inside a `SELECT` statement.

***

## Style 1 — `SEMANTIC_VIEW()` relation function

Use `SEMANTIC_VIEW(...)` in the `FROM` clause to specify exactly which metrics
and dimensions to retrieve, plus optional filtering and sorting. The database
inlines the semantic view as a derived subquery with the requested aggregation.

### Syntax

```SQL theme={null}
SELECT * FROM SEMANTIC_VIEW(
  [<db>.]<view_name>
  [METRICS   <table_alias>.<metric>  [, ...]]
  [DIMENSIONS <table_alias>.<dim>   [, ...]]
  [FACTS     <table_alias>.<fact>   [, ...]]
  [WHERE  <expr>]
  [HAVING <expr>]
  [ORDER BY <sort_expr> [ASC|DESC] [, ...]]
  [LIMIT  <n>]
) [AS <alias>]
```

All clauses inside `SEMANTIC_VIEW(...)` are **unordered** and optional, with
the exception of the view name which must appear first.

### Parameters

| Clause | Description |
| - | - |
| `view_name` | Fully-qualified or unqualified semantic view name. |
| `METRICS` | One or more `tableAlias.metricName` references. Only metrics defined in the semantic view are valid. |
| `DIMENSIONS` | One or more `tableAlias.dimensionName` references. Only dimensions defined in the semantic view are valid. |
| `FACTS` | One or more row-level references, which turns the query into a **detail query** — see [Detail queries](#detail-queries-facts). Cannot be combined with `METRICS` or `DIMENSIONS`. |
| `WHERE` | Filter applied to dimension/fact columns before aggregation. |
| `HAVING` | Filter applied to metric values after aggregation. |
| `ORDER BY` | Sorts the result. Accepts the same expressions as `METRICS`/`DIMENSIONS` references or positional integers. |
| `LIMIT` | Maximum number of rows to return. |

### Inlining behaviour

The database transforms Style-1 syntax into an equivalent SQL query:

```SQL theme={null}
SELECT <dim_exprs> AS <dim_names>, <metric_agg_exprs> AS <metric_names>
FROM   <root_table>
[LEFT | ASOF LEFT] JOIN <other_table> ON <join_conditions>
[...]
[WHERE  <where_expr>]
[GROUP BY 1, 2, ...]
[HAVING <having_expr>]
[ORDER BY <order_expr>]
[LIMIT <n>]
```

By default `LEFT JOIN` is used. Set
`enable_semantic_view_inner_join = true` to switch to `INNER JOIN`.

Only the tables the query needs appear in `FROM`. See
[Table pruning](#table-pruning-only-the-tables-a-query-needs) below.

### Examples

```SQL theme={null}
-- Metrics only (no GROUP BY in output)
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS orders.total_price
);

-- With dimensions (GROUP BY is implicit)
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS   orders.total_price, customer.cust_count
  DIMENSIONS orders.order_date
);

-- Clauses are unordered; DIMENSIONS can appear before METRICS
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  DIMENSIONS orders.order_date
  METRICS    orders.total_price
);

-- WHERE filters dimensions/facts; HAVING filters metrics
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS    orders.total_price
  DIMENSIONS orders.order_date
  WHERE   o_orderstatus = 'F'
  HAVING  orders.total_price > 10000
);

-- ORDER BY and LIMIT inside SEMANTIC_VIEW(...)
SELECT * FROM SEMANTIC_VIEW(
  sales_db.revenue_analysis
  METRICS    orders.avg_order_value
  DIMENSIONS orders.order_year
  ORDER BY orders.order_year DESC
  LIMIT 5
);

-- Assign an alias to the inlined subquery
SELECT sv.* FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS orders.total_price
) AS sv;
```

***

## Detail queries: `FACTS`

`FACTS` asks for the rows themselves instead of an aggregate. At row level a dimension is
just a fact the model also groups by, and a window metric has one value per row, so `FACTS`
accepts all three: declared facts, dimensions, and window metrics.

```SQL theme={null}
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  FACTS orders.order_key, orders.price, customer.cust_name
  WHERE o_orderstatus = 'F'
  ORDER BY orders.order_key
  LIMIT 100
);
```

The view is inlined with its join topology unchanged but **without `GROUP BY`**, so the
result keeps the grain of the root table:

```SQL theme={null}
SELECT `orders`.`o_orderkey` AS `order_key`, `orders`.`o_totalprice` AS `price`,
       `customer`.`c_name` AS `cust_name`
FROM `sales_db`.`orders` AS `orders`
LEFT JOIN `sales_db`.`customer` AS `customer`
  ON `orders`.`o_custkey` = `customer`.`c_custkey`
WHERE `orders`.`o_orderstatus` = 'F'
ORDER BY `orders`.`o_orderkey`
LIMIT 100;
```

Rules:

* `FACTS` cannot appear together with `METRICS` or `DIMENSIONS`: raw rows and aggregated rows
  have different grains, so a single query cannot ask for both.
* `HAVING` is rejected — there is no aggregation to filter. Put the predicate in `WHERE`.
* An **aggregate** metric is rejected: it has no row-level value. Request it with `METRICS`.
  A **window** metric is accepted.
* The view-level `FILTER` still applies, `AND`-ed with the query's own `WHERE`.

Detail queries are what makes ad-hoc SQL over several semantic views possible: each
`SEMANTIC_VIEW(...)` inlines to its own sub-query, and the outer query joins them on the
facts they expose.

```SQL theme={null}
SELECT a.order_key, b.shipped_qty
FROM SEMANTIC_VIEW(sales_db.order_metrics FACTS orders.order_key) a
JOIN SEMANTIC_VIEW(sales_db.shipment_metrics FACTS shipments.order_key, shipments.shipped_qty) b
  ON a.order_key = b.order_key;
```

***

## Validating the join topology: `EXPLAIN SNOWFLAKE`

`EXPLAIN SNOWFLAKE <query>` checks that a query joins its tables as a single **snowflake** —
every join edge pointing from the foreign-key side to a side whose join columns cover a unique
key, one root table, and every other table reachable from it. That is the condition under which
the row grain of the root table survives every join, so metrics cannot be silently inflated by a
fan-out.

```SQL theme={null}
EXPLAIN SNOWFLAKE
SELECT n.n_name, sum(o.o_totalprice)
FROM orders o
JOIN customer c ON o.o_custkey = c.c_custkey
JOIN nation n ON c.c_nationkey = n.n_nationkey
GROUP BY 1;
```

```plain theme={null}
Snowflake validation: OK
  scope #1: 3 relations, 2 edges, root = o
    relation o                        uk=<none>
    relation c                        uk=(c_custkey) [PRIMARY_KEYS]
    relation n                        uk=(n_nationkey) [PRIMARY_KEYS]
    edge     o (o_custkey) --equal--> c (c_custkey)   OK fk -> uk
    edge     c (c_nationkey) --equal--> n (n_nationkey)   OK fk -> uk
    verdict  snowflake OK; uk(result) = uk(o)
```

Uniqueness evidence comes from metadata only: the key columns of a primary-key, unique-key or
aggregate-key table, the `unique_constraints` table property, and — for a sub-query, CTE or
logical view — the `GROUP BY`, `SELECT DISTINCT` or `ROW_NUMBER() OVER (PARTITION BY ...) = 1`
that establishes uniqueness inside it.

The statement raises an error when the topology cannot be a snowflake: neither side of an equal
join is unique (the row grain would be lost), the query spans several independent snowflakes,
an `ON` clause carries no join key, or a single-inequality (ASOF-shaped) edge points at a side
that is not unique. Cases that metadata cannot decide are reported as explicit assumptions
rather than assumed away — a range join notes that it relies on the intervals never overlapping,
and an `ASOF JOIN` notes that the winner of a tie is unspecified.

***

## Reading a query's substrate: `EXPLAIN LINEAGE`

`EXPLAIN LINEAGE [JSON | TEXT] <query>` reports the facts about a query that a tool needs in
order to reason about it — the same join topology `EXPLAIN SNOWFLAKE` validates, plus what a
semantic-view recommendation depends on. The query is analysed and planned, never executed.

```SQL theme={null}
-- JSON, the default: for tools
EXPLAIN LINEAGE
SELECT c.c_nationkey, sum(o.o_totalprice)
FROM orders o JOIN customer c ON o.o_custkey = c.c_custkey
GROUP BY c.c_nationkey;

-- TEXT: the same substrate as a PlantUML mindmap, for people
EXPLAIN LINEAGE TEXT
SELECT c.c_nationkey, sum(o.o_totalprice)
FROM orders o JOIN customer c ON o.o_custkey = c.c_custkey
GROUP BY c.c_nationkey;
```

The substrate carries, for every join scope in the query: its relations, its join edges with the
direction and the evidence behind it, the unique keys found and where each came from, the output
columns with the aggregate that produced them, the filters, and any de-duplication. Alongside the
scopes it carries:

| Key | What it is |
| - | - |
| `sql` | the statement as written, with the `EXPLAIN` wrapper stripped and everything after it byte for byte — aliases, casing and comments are semantics |
| `plan` | the execution plan, or `plan_error` when planning fails where analysis succeeded. A join key written in `WHERE` only becomes a join edge in the plan, so without it a join condition cannot be told from a filter |
| `multi_source` | set operators and `FULL OUTER` joins, which decide whether the query is one snowflake or several stitched together |
| `windows` | ranking windows (`row_number`/`rank`/`dense_rank`), which are de-duplication candidates whose partition columns become a unique key, and every other window, which only adds a column |
| `internal_metrics` | aggregates that appear in `HAVING` or `ORDER BY` and never reach the output, but still constrain the result |
| `table_meta`, `view_meta`, `table_row_count` | each base table's `CREATE TABLE`, each logical view's defining `SELECT`, and each table's row count, keyed `db.table` exactly as a query dump keys them |

Column statistics are deliberately left out: large, and nothing in a recommendation depends on
them. A table whose DDL cannot be rendered is listed by name with the reason, rather than
dropping the whole section.

The TEXT rendering walks whatever the substrate contains rather than naming fields, so the two
serializations cannot drift apart: a key added later appears in both at once.

Every value stays on one bullet, however long it is: a plan, a `CREATE TABLE` or the statement
itself is a single fact, so the line breaks inside it are escaped as `\n` exactly as JSON escapes
them, rather than being spread over sibling bullets. Undoing the escape gives back the original
text character for character.

***

## Style 2 — plain table reference

Reference the semantic view as if it were a regular table. The database inlines
the view's columns into a wide subquery and exposes them with flat aliases of
the form `<tableAlias>__<columnName>`.

**Note**

Facts are projected only by a view that declares no `METRICS`. When a view
declares metrics, the inlined subquery is grouped at dimension grain, so a raw
fact column has no well-defined value there: projecting it would either be
invalid SQL or, if it were added to the grouping, change the grain and therefore
every metric value. Expose such a column as a dimension if you need to select it
alongside metrics.

### Syntax

```SQL theme={null}
SELECT <columns>
FROM [<db>.]<view_name> [AS <alias>]
[WHERE  <expr>]
[GROUP BY <exprs>]
[HAVING <expr>]
[ORDER BY <expr>]
[LIMIT  <n>]
```

### Flat column aliases

Each column from the semantic view is surfaced as
`<tableAlias>__<columnName>`.  For example, dimension `orders.order_date` is
exposed as `orders__order_date`, metric `orders.total_price` as
`orders__total_price`.

### Example

Given:

```SQL theme={null}
CREATE SEMANTIC VIEW sales_db.order_metrics
  TABLES (
    orders   AS sales_db.orders   PRIMARY KEY (o_orderkey),
    customer AS sales_db.customer PRIMARY KEY (c_custkey)
  )
  RELATIONSHIPS (
    ord_to_cust AS orders (o_custkey) REFERENCES customer
  )
  DIMENSIONS (
    orders.order_date AS o_orderdate
  )
  METRICS (
    orders.total_price AS SUM(o_totalprice)
  );
```

The following Style-2 query:

```SQL theme={null}
SELECT orders__order_date, orders__total_price
FROM   sales_db.order_metrics;
```

Is transparently rewritten to approximately:

```SQL theme={null}
SELECT orders__order_date, orders__total_price
FROM (
  SELECT o_orderdate AS orders__order_date,
         SUM(o_totalprice) AS orders__total_price
  FROM   sales_db.orders AS orders
  LEFT JOIN sales_db.customer AS customer
    ON orders.o_custkey = customer.c_custkey
  GROUP BY o_orderdate
) AS _sv;
```

***

## Several semantic view accesses in one query

A single query may reference as many semantic views as it needs, in either style and in
any mix. Each reference is inlined independently, so period-over-period reports — the
usual reason to want more than one — are written the same way as against ordinary tables:

```SQL theme={null}
-- Year-over-year, two Style-1 accesses of the same view
SELECT cur.order_date, cur.total_price, prev.total_price AS total_price_last_year
FROM SEMANTIC_VIEW(
       sales_db.order_metrics
       METRICS orders.total_price
       DIMENSIONS orders.order_date) AS cur
LEFT JOIN SEMANTIC_VIEW(
       sales_db.order_metrics
       METRICS orders.total_price
       DIMENSIONS orders.order_date) AS prev
  ON cur.order_date = years_add(prev.order_date, 1)
ORDER BY cur.order_date;

-- Current and prior period stacked, then aggregated
SELECT period, SUM(total_price)
FROM (
  SELECT 'cur' AS period, total_price
  FROM SEMANTIC_VIEW(sales_db.order_metrics METRICS orders.total_price
         DIMENSIONS orders.order_date WHERE orders.order_date >= '1995-01-01')
  UNION ALL
  SELECT 'prev' AS period, total_price
  FROM SEMANTIC_VIEW(sales_db.order_metrics METRICS orders.total_price
         DIMENSIONS orders.order_date WHERE orders.order_date < '1995-01-01')
) t
GROUP BY period;

-- Style 1 and Style 2 mixed, and two different views joined
SELECT s1.order_date, s1.total_price, s2.orders__total_price
FROM SEMANTIC_VIEW(sales_db.order_metrics METRICS orders.total_price
       DIMENSIONS orders.order_date) AS s1
JOIN sales_db.order_metrics AS s2
  ON s1.order_date = s2.orders__order_date;
```

**Note**

Give every reference an alias when the same view name appears more than once — including
two same-named views from different databases. A Style-2 reference is inlined as a
sub-query aliased by the view's bare name, so without aliases both references answer to
the same name and column references become ambiguous. A db-qualified column reference
(`db.view.column`) does not reach into the sub-query; use the alias instead.

***

## Table pruning: only the tables a query needs

A semantic view models a whole snowflake, but a single query rarely reads all of it. The
inlined query joins the smallest set of tables that covers the tables its projections
(`METRICS` / `DIMENSIONS` / `FACTS`) and its predicates (`WHERE`, `HAVING`, `ORDER BY`, and
the view-level `FILTER`) reference — plus whatever tables are needed to connect them.

```SQL theme={null}
-- Both the metric and the dimension live on `orders`: nothing else is joined.
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS    orders.total_price
  DIMENSIONS orders.order_month
);
-- FROM orders

-- The metric is on `line_items` and the dimension on `customers`, which have no
-- relationship of their own, so `orders` is joined back in to connect them.
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS    line_items.revenue
  DIMENSIONS customers.customer_name
);
-- FROM line_items LEFT JOIN orders ON ... LEFT JOIN customers ON ...
```

Pruning matters for results, not only for speed. A relationship declares a foreign key
pointing at a primary or unique key, so it is many-to-one and joining the referenced table
neither drops nor duplicates rows. When a model declares a relationship that is *not*
many-to-one — a station table joined to a device table on the station id, say — the
redundant join multiplies each row and every aggregate over it comes back inflated:
`COUNT(power_station.ps_id)` returned the number of devices, not the number of stations.

Pruning is skipped, and every declared table joined, when a predicate names a base-table
column directly (`WHERE o_orderstatus = 'F'`), since the model alone does not say which
table owns that column. Reference the fact or dimension instead
(`WHERE orders.order_status = 'F'`) to keep the query pruned.

## Session variables: table pruning

| Variable | Default | Description |
| - | - | - |
| `enable_semantic_view_table_pruning` | `true` | When `true`, the inlined query joins only the tables it needs. Set to `false` to join every table the view declares, as releases before this behaviour existed did. |
| `enable_semantic_view_table_pruning_on_inner_join` | `true` | Whether pruning also applies when `enable_semantic_view_inner_join = true`. Set to `false` to join every table in `INNER JOIN` mode while still pruning in the default `LEFT JOIN` mode. |

```SQL theme={null}
-- Join every table the view declares, in either join mode.
SET enable_semantic_view_table_pruning = false;

-- Prune under LEFT JOIN, but keep every join under INNER JOIN.
SET enable_semantic_view_table_pruning_on_inner_join = false;
```

**Note**

The second variable exists because an `INNER JOIN` is not inert the way a `LEFT JOIN` is. A
`LEFT JOIN` to a table nothing reads neither drops nor duplicates rows, so removing it cannot
change the answer. An `INNER JOIN` also drops the rows that fail to match, so a model that
relies on that filtering — treating the join as a data-quality gate rather than as a lookup —
can keep it. Pruning stays on by default in both modes: a relationship declares a foreign key,
and "only the tables the query needs" is what the model means either way.

## Session variable: `enable_semantic_view_inner_join`

| Variable | Default | Description |
| - | - | - |
| `enable_semantic_view_inner_join` | `false` | When `true`, `LEFT JOIN` is replaced with `INNER JOIN` (and `ASOF LEFT JOIN` with `ASOF INNER JOIN`) in the inlined query. |

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

***

## Inspecting the inline SQL: `EXPLAIN INLINE`

`EXPLAIN INLINE <query>` prints the *inline SQL* — the equivalent query where every
semantic-view reference has been expanded into its underlying base-table SQL (joins +
aggregation). The printed SQL is legal and directly executable: all identifiers are
quoted so the aliases remain valid.

This works for both query styles, and for semantic views used anywhere in the query
(including inside sub-queries and CTEs).

```SQL theme={null}
EXPLAIN INLINE
SELECT * FROM SEMANTIC_VIEW(
  sales_db.order_metrics
  METRICS   orders.total_price
  DIMENSIONS orders.order_date
);
```

Produces (approximately):

```SQL theme={null}
SELECT `order_metrics`.`order_date`, `order_metrics`.`total_price`
FROM (
  SELECT `orders`.`o_orderdate` AS `order_date`,
         SUM(`orders`.`o_totalprice`) AS `total_price`
  FROM `sales_db`.`orders` AS `orders`
  LEFT JOIN `sales_db`.`customer` AS `customer`
    ON `orders`.`o_custkey` = `customer`.`c_custkey`
  GROUP BY 1
) `order_metrics`;
```

**Note**

Only queries that actually reference a semantic view are expanded. If the query
touches **no** semantic view, `EXPLAIN INLINE` returns the query unchanged.

The same expansion is available over HTTP via the semantic view inline REST endpoint,
`POST /api/v2/catalogs/{catalog}/databases/{db}/semantic_views/inline`.

***

## See also

* [CREATE SEMANTIC VIEW](/documents/4.2/sql-reference/sql-statements/semantic-view/CREATE_SEMANTIC_VIEW.md)
* [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.