Query Language¶
OrionBelt uses a structured query object to express analytical queries against a semantic model. The query language selects dimensions and measures, applies filters, sorts results, and limits output — all using business names rather than raw SQL.
Query Object Structure¶
select:
dimensions:
- Customer Country
- "Order Date:month" # with time grain
measures:
- Revenue
- Order Count
where:
- field: Customer Segment
op: in
value: [SMB, MidMarket]
having:
- field: Revenue
op: gt
value: 10000
orderBy:
- field: Revenue
direction: desc
nulls: last # optional — "first" | "last"; omit for dialect default
limit: 1000
offset: 0 # optional, paired with limit for pagination
In Python¶
from orionbelt.models.query import (
QueryObject,
QuerySelect,
QueryFilter,
QueryOrderBy,
FilterOperator,
SortDirection,
)
query = QueryObject(
select=QuerySelect(
dimensions=["Customer Country", "Order Date:month"],
measures=["Revenue", "Order Count"],
),
where=[
QueryFilter(field="Customer Segment", op=FilterOperator.IN, value=["SMB", "MidMarket"]),
],
having=[
QueryFilter(field="Revenue", op=FilterOperator.GT, value=10000),
],
order_by=[QueryOrderBy(field="Revenue", direction=SortDirection.DESC)],
limit=1000,
)
Select¶
The select section specifies which dimensions and measures to include.
The result has the dimensions first, then the measures, each in the order
select lists them, so a column position in orderBy (field: "3") names
the third of them.
Dimensions¶
Dimensions are referenced by name as defined in the semantic model. They become GROUP BY columns in the generated SQL.
Time Grain Override¶
Apply a time grain at query time using "dimension:grain" syntax:
select:
dimensions:
- "Order Date:month" # truncate to month
- "Order Date:quarter" # truncate to quarter
- "Order Date:year" # truncate to year
Supported grains: year, quarter, month, week, day, hour, minute, second.
This overrides any timeGrain set on the dimension definition.
The result column is named after the dimension: Order Date. When the query selects one dimension at more than one grain, as above, the first keeps that name and each other one is named with its grain, Order Date:quarter and Order Date:year (Order Date:value for the column without a grain), which is also the name orderBy uses. A measure's grain override names the dimension, so exclude: [Order Date] drops it at every grain the query selects. Cumulative and window metrics order by their time dimension and then by its other grains in the query, so the months of a year are not ties. A period-over-period metric compares at its own grain, so its time dimension can be selected only once (INVALID_METRIC).
Two things are checked before the query is answered rather than after.
The underlying column must carry a date: a grain compiles to
date_trunc(grain, column), which no engine will evaluate over text, so a grain
over a string column is rejected with TIME_GRAIN_ON_NON_TEMPORAL rather than
left to fail in the engine's binder.
The dimension's resultType must also be wide enough to hold the grain the
query asks for: a temporal resultType is emitted as a CAST around the
truncation, in the GROUP BY as well as the projection, so asking for hour on
a dimension declaring date would merge the hours of a day into one row and sum
their measures. That query is rejected with RESULT_TYPE_LOSES_GRAIN rather
than answered - hour, minute and second need timestamp, and neither
time nor time_tz takes a grain at all, because a grain always carries a
date. A non-temporal resultType is not cast and takes any grain.
A grain must also be one the column's values can answer. A column of month
starts (a date_trunc('month', ...) computed column, or one declaring
grain: month) answers month, quarter and year; day or week of it
would return the month starts labelled as days, and is rejected with
GRAIN_FINER_THAN_DECLARED. See
Columns that hold a grain.
Coalesce (Merging Role-Playing Dimensions)¶
Role-playing dimensions (e.g. Sales Employee and Purchase Employee, both pointing to Employees.Employee Name via different facts) appear as separate columns in CFL output — one row per role per person. To collapse them into a single output column, use a coalesce group inside dimensions:
select:
dimensions:
- coalesce: [Employee Name, Purchase Employee]
as: Employee
measures:
- Total Sales
- Total Purchase Qty
Each leg still projects only its own role-playing dimension (others NULL); the outer wrapper emits COALESCE("Employee Name", "Purchase Employee") AS "Employee" and groups by it. A person who is both a sales rep and a purchase employee shows up as one row with totals on both sides.
Rules:
- At least 2 members; all must be existing model dimensions
- All members must share the same
resultType - The
asalias must not collide with any model dimension or measure name orderBymay reference the alias directly (field: Employee) — ordering happens in the outer wrapper where the alias is in scope- Without
orderBy, a query withlimit,rolluporcubeis sorted by the alias, as by any other dimension - Over two facts, a running total, or a window metric ordered by a date the query coalesces (the window's own date, or another dimension on its date column), can't be selected beside a coalesce group (
INCOMPATIBLE_COMBINATION). Totals, grain overrides, window metrics over other dimensions and metrics over totals work as with any dimension wherefilters belong on the underlying dimension names (filtering is applied per leg, before the COALESCE collapses the values)
Error codes: COALESCE_MISSING_ALIAS, DUPLICATE_COALESCE_ALIAS, COALESCE_ALIAS_COLLISION, COALESCE_TOO_FEW_MEMBERS, COALESCE_TYPE_MISMATCH.
Measures¶
Measures are referenced by name. They can be simple aggregations, expression-based measures, or metrics.
Raw Mode (select.fields)¶
Raw mode returns un-aggregated rows from one or more data objects, projecting physical columns directly. It is the right choice when you need detail rows rather than aggregated metrics — e.g., exporting a transaction list, building a row-level export, or feeding a downstream tool that does its own aggregation.
select:
fields:
- Customers.Country
- Orders.Order ID
- Orders.Amount
distinct: false
where:
- field: Orders.Amount
op: gt
value: 100
orderBy:
- field: Orders.Amount
direction: desc
limit: 100
Compiles to a flat SELECT field1, field2, ... FROM base [LEFT JOIN ...] [WHERE ...] [ORDER BY ...] [LIMIT n] — no GROUP BY, no aggregates.
Field references¶
Each entry in fields is a qualified DataObject.Column reference to a physical column in the model. Logical dimension/measure names are not accepted in raw mode — use dimensions / measures for those.
The output column is aliased to the original "DataObject.Column" reference so result rows are self-describing.
distinct¶
Set select.distinct: true to emit SELECT DISTINCT, deduplicating rows after projection. Outside raw mode this flag is rejected.
What's excluded in raw mode¶
Raw mode is mutually exclusive with aggregate features. The following are rejected at validation time:
select.dimensionsselect.measureshaving(HAVING references measures, which raw mode doesn't have)dimensionsExclude
Filters and ordering in raw mode¶
- WHERE: same operators as aggregate mode. Filter fields can reference a dimension name (resolved to its physical column) or a qualified
DataObject.Column. - ORDER BY: must reference a
DataObject.Columnalias fromselect.fields, or a 1-based numeric position.
Joins and fanout¶
Raw mode reuses the model's directed join graph: when fields span multiple data objects connected by many-to-one joins, the planner walks the graph and emits the necessary LEFT JOINs. Fanout protection still applies — reversed many-to-one joins (which would multiply rows on the "one" side) are rejected. Fields of data objects on different data sources are read by a federated query.
Multi-fact raw queries (raw CFL)¶
When select.fields references columns from independent fact tables — facts that share a common dimension via reverse many-to-one joins but are not connected to each other directly — the planner emits a Composite Fact Layer: one UNION ALL leg per leg-root fact, with NULL-padding for fields not reachable from that leg. The outer query selects from the composite CTE.
# Customers ← Orders (m:1)
# Customers ← Returns (m:1)
select:
fields:
- Customers.Name
- Orders.Order ID
- Orders.Amount
- Returns.Return ID
- Returns.Refund
distinct: true
Compiles roughly to:
WITH composite_raw_01 AS (
SELECT c.NAME AS "Customers.Name",
o.ORDER_ID AS "Orders.Order ID",
o.AMOUNT AS "Orders.Amount",
CAST(NULL AS VARCHAR) AS "Returns.Return ID",
CAST(NULL AS FLOAT) AS "Returns.Refund"
FROM ORDERS o LEFT JOIN CUSTOMERS c ON o.CUSTOMER_ID = c.CUSTOMER_ID
UNION ALL
SELECT c.NAME, CAST(NULL AS VARCHAR), CAST(NULL AS FLOAT),
r.RETURN_ID, r.REFUND
FROM RETURNS r LEFT JOIN CUSTOMERS c ON r.CUSTOMER_ID = c.CUSTOMER_ID
)
SELECT DISTINCT * FROM composite_raw_01
A "leg root" is a fact data object referenced by some field that is not reachable from another field's source via directed joins — i.e. it is maximal under reachability. Each leg root yields one UNION ALL leg. Conformed dim columns (those reachable from every leg) project the same value across legs and line up; fact-specific columns are typed CAST(NULL AS …) in legs that don't cover them. distinct: true is applied once at the outer query — the most portable place.
WHERE filters are applied to legs whose joined objects contain all the filter's referenced data objects; a leg that cannot reach a query filter lists its rows without it, with a FILTER_NOT_APPLIED warning naming the leg's fact. ORDER BY is remapped to the field aliases at the outer level. A static model filter a leg cannot reach is skipped with a STATIC_FILTER_NOT_APPLIED warning, or, declared enforce: always, refuses the query (STATIC_FILTER_UNREACHABLE).
UNION ALL BY NAME optimization (DuckDB, Snowflake)¶
DuckDB and Snowflake both support UNION ALL BY NAME, which aligns columns by name across legs and auto-fills any missing columns with NULL. On these dialects the planner skips the per-leg CAST(NULL AS …) padding entirely and emits only the columns each leg actually has — the database does the rest:
-- DuckDB / Snowflake
WITH composite_raw_01 AS (
SELECT c.NAME AS "Customers.Name", o.ORDER_ID AS "Orders.Order ID", o.AMOUNT AS "Orders.Amount"
FROM ORDERS o LEFT JOIN CUSTOMERS c ON o.CUSTOMER_ID = c.CUSTOMER_ID
UNION ALL BY NAME
SELECT c.NAME, r.RETURN_ID AS "Returns.Return ID", r.REFUND AS "Returns.Refund"
FROM RETURNS r LEFT JOIN CUSTOMERS c ON r.CUSTOMER_ID = c.CUSTOMER_ID
)
SELECT DISTINCT * FROM composite_raw_01
The other six dialects (BigQuery, ClickHouse, Databricks, Dremio, MySQL, Postgres) keep the explicit typed-NULL padding shown above. Output rows are identical either way; the optimization is purely about leg readability and slightly less SQL the database has to parse.
Secondary Join Paths¶
When a model defines secondary joins (e.g., Flights → Airports via departure and arrival), use usePathNames to select which join path to use:
select:
dimensions:
- Airport Name
measures:
- Total Ticket Price
usePathNames:
- source: Flights
target: Airports
pathName: arrival
Each entry specifies a (source, target, pathName) triple. The pathName must match a secondary join defined in the model. When active, the secondary join replaces the primary join for that pair.
In Python¶
from orionbelt.models.query import QueryObject, QuerySelect, UsePathName
query = QueryObject(
select=QuerySelect(
dimensions=["Airport Name"],
measures=["Total Ticket Price"],
),
use_path_names=[
UsePathName(source="Flights", target="Airports", path_name="arrival"),
],
)
In JSON (full mode)¶
{
"select": {
"dimensions": ["Airport Name"],
"measures": ["Total Ticket Price"]
},
"usePathNames": [
{"source": "Flights", "target": "Airports", "pathName": "arrival"}
]
}
If a usePathNames entry references a non-existent data object or pathName, the query will return a resolution error.
usePathNames applies to the whole query, so it selects one join per pair: a query cannot ask for the departure and the arrival airport at the same time this way. For that, declare role dimensions in the model with via and pathName (see Several Roles in One Query). Each role joins its own aliased copy of the table and ignores usePathNames.
Dimension Exclusion (Anti-Join)¶
The dimensionsExclude flag inverts a dimension-only query to return value combinations that do not exist in the data. This is useful for finding missing relationships — for example, directors and producers who have never collaborated on a movie.
This generates an anti-join query using SQL EXCEPT:
- All possible combinations — A
CROSS JOINof the distinct values of each dimension - Existing combinations — The actual dimension pairs found through the join graph. Where several data objects join the dimensions (movies and series both joining directors and producers), a pair any of them holds exists.
- Result — All combinations
EXCEPTexisting ones
Constraints¶
- No measures allowed —
dimensionsExcludeonly works with dimension-only queries (no measures or metrics) - 2+ dimensions required — At least two dimensions must be specified
In Python¶
from orionbelt.models.query import QueryObject, QuerySelect
query = QueryObject(
select=QuerySelect(dimensions=["Director", "Producer"]),
dimensions_exclude=True,
)
In JSON¶
Error Codes¶
| Error Code | Cause |
|---|---|
DIMENSIONS_EXCLUDE_WITH_MEASURES |
Query includes measures — not allowed with dimensionsExclude |
DIMENSIONS_EXCLUDE_INSUFFICIENT |
Fewer than 2 dimensions specified |
Accepting Fan-Out (allowFanOut)¶
A measure that reads both a base-grain column and one from a data object the
query's joins replicate is evaluated once per base row, so the replicated column
contributes once per duplicate. That is intended for a per-unit rate
(quantity * list price) and wrong for a column carrying the replicated row's
own magnitude, and nothing in the model separates the two. Such a query compiles
with a FAN_TRAP_RISK warning.
Set allowFanOut on the query to record that the duplication is intended:
This only suppresses the warning; the generated SQL is unchanged. The
measure-level allowFanOut is stronger: in the grain-deduplication pass it also
skips the rewrite.
As-of Date (asOf)¶
A cumulative metric whose timeDimension the query does not select is
evaluated as of one period, per group of the selected dimensions: the value
its row for that period would show with the time dimension selected. asOf
names the date; it is read at the time dimension's grain, so 2025-12-17 is
December for a monthly year-to-date and that day for a daily rolling window.
Over weeks it is the week holding the date: as of a Saturday, February 1, a
month-to-date reads January if that week began in January.
{
"select": { "dimensions": ["Region"], "measures": ["Revenue", "Revenue YTD"] },
"asOf": "2025-12-17"
}
Without asOf the metric is evaluated at the latest period with data under
the query's filters. A time filter therefore picks the period: filtered to
Order Month < 2025-07-01, year-to-date is June's, read from January. The
plain measures respect the filter as usual. A group without data in the
metric's range gets NULL, except a count, which is never NULL: a
cumulativeType: count metric, or a running sum of a count measure, reads
0 there.
asOf has no effect on a cumulative metric whose time dimension is selected,
and a query that sets it with no such metric compiles with a
CUMULATIVE_CONSTRAINT_VIOLATED warning. The SQL surfaces (OBSQL, Flight SQL,
the Postgres wire) have no asOf; a time filter's upper bound picks the
period there.
Filling Empty Periods (fill)¶
A query returns the periods that have rows. fill: true returns every period
of its time dimension, also those without:
{
"select": { "dimensions": ["Region", "Order Month"], "measures": ["Revenue", "Order Count"] },
"where": [{ "field": "Order Month", "op": "between", "value": ["2024-01-01", "2024-06-30"] }],
"fill": true
}
| Time dimension | Exactly one selected dimension at a time grain of a day or longer, with resultType date or timestamp |
| Range | The periods the where admits (gte, gt, lte, lt, between). A filter on the dimension itself compares its periods, as it does without fill: gte 2023-12-15 starts in January, gte 2023-12-01 in December, lte 2024-04-15 ends in April. A filter on the date itself (a dimension without a grain, or Orders.Order Date) admits every period holding an admitted day: Order Day gte 2023-12-15 starts in December. Bounds count at the top level and inside a logic: and group. A side without a single constant bound runs to the first or last period with data. The range never cuts the data off |
| Other dimensions | Crossed with the periods: every member the query returns, a NULL member included, gets every period |
| Empty values | A count is 0, a measure with a defaultValue reads it, anything else is NULL, a derived metric included |
| Rows without a period | A row whose time is NULL (an order without a date) stays a row of its own |
| Cumulative metrics | An empty period shows what its window holds as of that period: a running total carries the last value on, a rolling window drops the periods it no longer reaches, a grain-to-date metric starts again in a new year or quarter and is NULL until it has rows. A count is never NULL: a cumulativeType: count metric, or a running sum of a count measure, reads 0 in a window that reaches no period with rows. A period with rows shows what it shows without fill, and a time filter does not shorten a window. The metric's timeDimension has to be the dimension being filled |
| ORDER BY, LIMIT | Apply to the filled rows |
The empty periods are added to the rows the query computed, so a feature that
reads those rows is refused with it: grouping: rollup/cube, having, a
total: true measure, window and period-over-period metrics, a cumulative
metric over another time dimension, and a cumulative metric over a reaggregate
metric (FILL_COMBINATION_NOT_SUPPORTED). The SQL surfaces (OBSQL, Flight SQL, the
Postgres wire) have no fill.
Filters¶
Filters restrict the result set. Dimension filters go in where (become SQL WHERE), and measure filters go in having (become SQL HAVING).
where:
# By dimension name
- field: Customer Country
op: equals
value: Germany
# By qualified column (DataObject.Column) — no dimension needed
- field: Orders.Order Status
op: equals
value: F
having:
- field: Revenue
op: gte
value: 5000
Multiple top-level filters are combined with AND. For OR logic or more complex boolean expressions, use filter groups.
Filter Structure¶
| Property | Type | Description |
|---|---|---|
field |
string | Dimension name or DataObject.Column (where), measure name (having) |
op |
string | Filter operator (see table below) |
value |
any | Comparison value (string, number, boolean, date, list, etc.) |
Date and timestamp values are supported as ISO 8601 strings. All variants work: "2026-01-01", "2026-01-01T14:30:00", "2026-01-01T00:00:00Z", "2026-01-01T14:30:00+02:00". When constructing queries in Python, datetime.date and datetime.datetime objects are automatically coerced to ISO strings.
{
"where": [
{ "field": "Order Date", "op": ">=", "value": "2026-01-01" },
{ "field": "Created At", "op": ">=", "value": "2026-01-01T00:00:00Z" },
{ "field": "Order Date", "op": "<", "value": "2027-01-01" }
]
}
Filtering a time-grained dimension¶
A filter on a dimension with a timeGrain compares the period the dimension
shows, not the date inside it. With Order Month at month grain:
| Filter | Admits |
|---|---|
Order Month equals 2025-01-01 |
January, all of it |
Order Month equals 2025-01-20 |
nothing: no month starts on the 20th |
Order Month gte 2025-01-15 |
February on: January starts before the 15th |
Order Month lte 2025-01-15 |
up to January, all of it |
The comparison is at the dimension's own grain, whatever grain the query shows
it at: Order Month gte 2025-01-15 also starts in February when the query
selects Order Month:day. To compare dates, filter the date itself: a
dimension on the same column without a grain, or the qualified column
(Orders.Order Date). A week compares its first day (Monday, or the model's
weekStart), and a timestamp period its start at midnight. The same holds
wherever a filter names the dimension: a measure's filterContext.include item
and a filter inside an exists subquery compare the period too.
The filter compiles to the truncated column (CAST(DATE_TRUNC('month', ...)
AS DATE) >= '2025-01-15'), which an engine cannot use to prune partitions or
use an index on the date. Where that matters, a filter on the date itself,
written with period starts, admits the same rows.
Filter Groups (AND / OR / NOT)¶
A filter group combines multiple filters with and or or logic. Groups can be nested recursively for complex boolean expressions.
where:
# Simple OR: country is US or CA
- logic: or
filters:
- field: Customer Country
op: equals
value: US
- field: Customer Country
op: equals
value: CA
Nested groups: (A OR B) AND C¶
where:
- logic: and
filters:
- logic: or
filters:
- field: Customer Country
op: equals
value: US
- field: Customer Country
op: equals
value: CA
- field: Market Segment
op: equals
value: BUILDING
Negation: NOT (A OR B)¶
where:
- logic: or
negated: true
filters:
- field: Order Status
op: equals
value: P
- field: Order Status
op: equals
value: F
Filter Group Properties¶
| Property | Type | Default | Description |
|---|---|---|---|
logic |
enum | and |
and or or — how to combine child filters |
filters |
list | — | Child filters (leaf filters or nested filter groups) |
negated |
bool | false |
Wrap the combined expression with NOT |
Filter groups and leaf filters can be mixed freely at any level — in where, having, or nested inside other groups.
In Python¶
from orionbelt.models.query import (
QueryFilter, QueryFilterGroup, FilterOperator,
)
# (country = 'US' OR country = 'CA') AND segment = 'BUILDING'
where = [
QueryFilterGroup(
logic="and",
filters=[
QueryFilterGroup(
logic="or",
filters=[
QueryFilter(field="Customer Country", op=FilterOperator.EQ, value="US"),
QueryFilter(field="Customer Country", op=FilterOperator.EQ, value="CA"),
],
),
QueryFilter(field="Market Segment", op=FilterOperator.EQ, value="BUILDING"),
],
),
]
Filter Reachability¶
A where filter field can reference:
- A dimension name (e.g.
Order Priority) — resolves to the dimension's data object and column - A qualified column using
DataObject.Columndot notation (e.g.Orders.Order Priority) — directly references a column without requiring a dimension definition
The referenced data object must be reachable from the query's join graph:
- Directly joined in the query (base object or any object in the join path)
- A descendant — reachable via directed joins from any already-joined object
If the data object is reachable but not yet in the join path, it is auto-joined automatically. If the data object is not reachable at all, the query is refused with UNREACHABLE_FILTER_OBJECT: answering it without the filter would return rows the filter excludes.
When the measures span independent facts (a CFL union), each leg applies the filter if its fact reaches the filter's data object. If one leg cannot, that leg's measures are computed without the filter, and the query returns a FILTER_NOT_APPLIED warning naming them: they are what that fact holds, and the filter has no bearing on them. Static model filters: are different: they are declared once for every query and, by default, apply where relevant, so a query or leg that cannot reach one skips it with a STATIC_FILTER_NOT_APPLIED warning. A static filter declared enforce: always refuses such a query instead (STATIC_FILTER_UNREACHABLE); see Static Filters.
Filters on the many side of a join¶
A WHERE filter on a data object on the many side of the measures' objects (an Orders column, with measures on Customers) answers the question SQL's Customers LEFT JOIN Orders WHERE <filter> does, each customer counted once:
- A customer with orders counts when one of its orders passes the filter.
Status = okis "customers with an ok order", and several order conditions in one filter must hold for the same order. - A customer without orders counts when the filter holds with every order column NULL:
Tier = gold or Status = okkeeps a gold customer who has never ordered, andOrders.Order IDnotsetlists the customers without orders.NOT (Status = bad)does not keep them, since a comparison with NULL is not true. - Grouped by an order column (
Status), the customers without orders form the NULL group; measures on the orders read 0 or NULL there.
The two kinds of customer are planned as two sets that do not overlap: the order rows the filter accepts, each customer deduplicated, and the customers with no order at all, read without joining the orders. Neither multiplies the other. The second set is added only when the filter can accept such a customer, so Status = ok plans exactly as before.
Without a filter the customers without orders are added the same way: a customer measure reads the same beside an order measure as alone, and an order without a customer stays a row too (its customer columns NULL), so the rows add up. See Parents without children.
A shape that cannot carry the second set is refused with FILTER_ADMITS_ROWS_WITHOUT rather than leaving those customers out: a nested data object, a measure with allowFanOut: true on that side, or measures on several one-side objects under grouping: rollup / cube. Measures on several one-side objects otherwise get a set each (customers without orders, products never ordered). exists / nonexists states the question directly:
where:
- logic: or
filters:
- {field: Tier, op: "=", value: gold}
- field: Customers.Customer ID
op: exists
subquery: {dataObject: Orders, filter: [{field: Status, op: "=", value: ok}]}
A having filter field must reference a measure name.
Filter Operators¶
OrionBelt supports two operator naming conventions — OBML style and SQL style. Both are equivalent.
Comparison Operators¶
| OBML | SQL Style | SQL Output | Value Type |
|---|---|---|---|
equals |
=, eq |
= value |
scalar |
notequals |
!=, neq |
<> value |
scalar |
gt |
>, greater |
> value |
scalar |
gte |
>=, greater_eq |
>= value |
scalar |
lt |
<, less |
< value |
scalar |
lte |
<=, less_eq |
<= value |
scalar |
Set Operators¶
| OBML | SQL Style | SQL Output | Value Type |
|---|---|---|---|
inlist |
in |
IN (v1, v2, ...) |
list |
notinlist |
not_in |
NOT IN (v1, v2, ...) |
list |
Null Operators¶
| OBML | SQL Style | SQL Output | Value Type |
|---|---|---|---|
set |
is_not_null |
IS NOT NULL |
none |
notset |
is_null |
IS NULL |
none |
blank |
— | (col IS NULL OR TRIM(col) = '') |
none |
notblank |
— | (col IS NOT NULL AND TRIM(col) <> '') |
none |
blank / notblank go beyond is_null: they also treat a string of whitespace-only characters as empty, which is the practical "missing value" check for free-text columns.
String Operators¶
| Operator | SQL Output | Value Type |
|---|---|---|
contains |
LIKE '%value%' (dialect-specific) |
string |
notcontains |
NOT LIKE '%value%' |
string |
starts_with |
LIKE 'value%' |
string |
ends_with |
LIKE '%value' |
string |
like |
LIKE 'pattern' |
string |
notlike |
NOT LIKE 'pattern' |
string |
ilike |
ILIKE 'pattern' (dialect-specific) |
string |
notilike |
NOT ILIKE 'pattern' (dialect-specific) |
string |
ilike / notilike match case-insensitively. Postgres, Snowflake, DuckDB,
Databricks and ClickHouse use ILIKE; Dremio uses its ILIKE(value, pattern, escape)
function; BigQuery and MySQL, which have no ILIKE, compare LOWER of both
sides. Non-ASCII letters fold on every engine ('ÄRGER' matches 'är%').
In a like / ilike pattern, a backslash escapes the next %, _ or
backslash: a\_b matches a_b but not axb. This holds on every engine.
DuckDB, Dremio and Snowflake get an explicit ESCAPE '\', because they read the
backslash literally without one. contains, starts_with and ends_with take
a plain value and escape its wildcards themselves.
Regex Operators¶
| Operator | Value Type | Notes |
|---|---|---|
regex |
string (regex pattern) | Match values against a regular expression |
notregex |
string (regex pattern) | Inverse of regex |
Regex syntax is delegated to the target dialect's native regex engine, so the flavour of regex differs per dialect. The compiler emits dialect-appropriate SQL:
| Dialect | Generated SQL |
|---|---|
| Postgres | (col ~ 'pattern') / (col !~ 'pattern') (POSIX) |
| DuckDB | regexp_matches(col, 'pattern') (RE2) |
| ClickHouse | match(col, 'pattern') (RE2) |
| BigQuery | REGEXP_CONTAINS(col, 'pattern') (RE2) |
| MySQL | (col REGEXP 'pattern') (POSIX-extended via ICU) |
| Databricks | (col RLIKE 'pattern') (Java regex) |
| Snowflake, Dremio | REGEXP_LIKE(col, 'pattern') (POSIX-extended) |
Use only the common subset of regex features (anchors, character classes, alternation, basic quantifiers) if a query has to be portable across dialects. Backreferences, lookarounds, and named groups are not portable.
String Length Operators¶
| Operator | SQL Output | Value Type |
|---|---|---|
length_eq |
LENGTH(col) = N |
integer |
length_gt |
LENGTH(col) > N |
integer |
length_lt |
LENGTH(col) < N |
integer |
Useful for filtering on padded codes, fixed-width identifiers, or detecting truncated strings. The value must be a non-negative integer.
Range Operators¶
| Operator | SQL Output | Value Type |
|---|---|---|
between |
BETWEEN low AND high |
list of 2 |
notbetween |
NOT BETWEEN low AND high |
list of 2 |
relative |
Relative time range | object |
Relative filter object
The relative operator expects an object with the following keys:
unit: one ofday,week,month,quarter,yearcount: positive integer number of unitsdirection(optional):past(default) orfutureinclude_current(optional): boolean, defaulttruecalendar(optional): boolean, defaultfalse. Whole calendar periods instead of a rolling window (see below)toDate(optional): boolean, defaultfalse. Withcalendar, the current period ends today
Example (last 7 days, inclusive of today):
where:
- field: Order Date
op: relative
value:
unit: day
count: 7
direction: past
include_current: true
Without calendar, the window rolls: {unit: month, count: 3} is the three months back from today, starting on today's day of the month. With calendar: true, it counts whole periods from the start of the current one, so "this quarter" and "last full month" mean what they say:
| Value | Range (today 2025-05-20) |
|---|---|
{unit: quarter, count: 1, calendar: true} |
This quarter: 2025-04-01 to 2025-06-30 |
{unit: month, count: 1, calendar: true, include_current: false} |
Last full month: 2025-04-01 to 2025-04-30 |
{unit: quarter, count: 4, calendar: true, include_current: false} |
The last four full quarters: 2024-04-01 to 2025-03-31 |
{unit: month, count: 3, calendar: true} |
This month and the two before: 2025-03-01 to 2025-05-31 |
{unit: year, count: 1, calendar: true, toDate: true} |
Year to date: 2025-01-01 to 2025-05-20 |
{unit: month, count: 2, calendar: true, direction: future, include_current: false} |
The next two full months: 2025-06-01 to 2025-07-31 |
A week starts on the model's weekStart (Monday by default). toDate needs calendar: true, include_current: true and direction: past; anything else is INVALID_RELATIVE_FILTER.
Today is the date in the model's queryTimezone where it sets one, the zone its timestamps are read in; else the database session's.
Period Literals¶
A filter on a date or timestamp field also accepts a period as its value: a year ('2025'), a quarter ('2025-Q1') or a month ('2025-03'). It stands for the whole period, so the comparison holds for every day in it, including the last day's times on a timestamp:
| Filter | Means |
|---|---|
{op: "=", value: "2025-Q1"} |
2025-01-01 up to, not including, 2025-04-01 |
{op: "<=", value: "2024-12"} |
Before 2025-01-01, all of December included |
{op: ">", value: "2025-Q1"} |
From 2025-04-01 |
{op: between, value: ["2025-01", "2025-03"]} |
2025-01-01 up to, not including, 2025-04-01 |
{op: in, value: ["2025-Q1", "2025-07-04"]} |
The first quarter, or 4 July |
=, !=, <, <=, >, >=, in, not_in, between and notbetween take periods, and a period can sit beside an ISO date in a list. Another operator with a period value is INVALID_FILTER_VALUE. A value that is not one of these shapes, such as '2025-01-15', is compared as before, and a field that is not a date keeps the value as it is: Batch = '2025' compares the string. Periods are read the same way wherever a filter names a date field: in where, inside an exists subquery's filter, in a measure's filterContext.include and in a static model filter. A period whose bounds fall outside 0001-01-01 to 9999-12-31 ('0000', '9999-12') is INVALID_FILTER_VALUE.
String contains is dialect-aware
The contains operator generates different SQL per dialect:
- Postgres/ClickHouse:
ILIKE '%' || value || '%' - Snowflake:
CONTAINS(column, value) - Dremio/Databricks:
LOWER(column) LIKE '%' || LOWER(value) || '%'
Existence Operators¶
exists / nonexists express "this row has (or doesn't have) a matching row in a related data object" as a correlated EXISTS (SELECT 1 FROM …) subquery. The first-class primitive for regulatory data-quality rules, coverage and anti-join reports, and any "parent has at least one child of kind X" question.
| Operator | SQL Output | Payload |
|---|---|---|
exists |
EXISTS (SELECT 1 FROM target WHERE target.k = subject.k …) |
subquery object |
nonexists |
NOT EXISTS (…) |
subquery object |
Both operators take a subquery: object (not value:) describing the target and any extra predicates restricting which target rows count:
where:
- field: Order ID
op: exists
subquery:
dataObject: OrderItems # target — reachable from the subject's data object
filter: # optional predicates on the target rows
- field: Is Returned
op: equals
value: true
For "orders with no payment":
The join columns are not restated — the planner walks the model's existing joins: from the subject's data object to subquery.dataObject. When multiple secondary joins exist between subject and target, pin the path with pathName::
where:
- field: Order ID
op: exists
subquery:
dataObject: Returns
pathName: viaWarehouse # matches a declared secondary join's pathName
Subquery filter rules
subquery.filter accepts the same operator vocabulary as the outer filter, including another exists / nonexists. An inner one correlates to the data object its field is on, inside the subquery around it: that object is joined into the body when the path did not already read it, and it cannot be the outer subject (filter that in the outer where).
Its field resolves like an outer where field, minus measure names — a correlated subquery filters rows, not aggregates:
- a column on the target data object (e.g.
Is ReturnedonOrderItems), - a dimension name,
- a qualified
DataObject.Column.
A field on a different data object is joined in inside the subquery, so a semi-join can be windowed by something one or more joins past the target:
where:
- field: Customer Country # subject: Customers
op: exists
subquery:
dataObject: Orders # target
filter:
- field: Order Year # dimension on Dates, one join past Orders
op: equals
value: 2024
EXISTS (
SELECT 1 FROM ORDERS "Orders"
INNER JOIN DATES "Dates" ON "Orders"."DATE_KEY" = "Dates"."DATE_KEY"
WHERE "Customers"."CUSTOMER_ID" = "Orders"."CUSTOMER_ID" AND "Dates"."YEAR" = 2024
)
Two rules bound the traversal:
- The object must be reachable from the target by the same forward-only join walk the outer query uses, or the filter is rejected (
UNREACHABLE_SUBQUERY_FILTER_OBJECT) rather than silently dropped. - It must not be, or be reached through, the subject of the correlation (
SUBQUERY_FILTER_OBJECT_NOT_JOINABLE): joining the subject inside the body would shadow its outer alias and rebind the correlation predicate to the subquery's own rows. Filter the subject in the outerwhereinstead.
A column of the target wins over a same-named dimension, so adding a dimension to a model never changes what an existing subquery filter compiles to.
exists / nonexists are WHERE-only. Both operators are rejected in having: with INVALID_FILTER_OPERATOR because the correlation predicate references the subject's row-level column, which is out of scope after GROUP BY. Measure-level EXISTS — "groups where some matching child row exists" — is a deferred follow-up (MeasureFilter.subquery).
EXISTS is portable — all 8 dialects compile the same shape, only identifier quoting differs.
Ordering¶
Sort results by dimension or measure names from the query's SELECT, by a measure or metric the query does not select, or by numeric position:
orderBy:
- field: Revenue
direction: desc
- field: Customer Country
direction: asc # default
- field: "1" # numeric position (1-based)
direction: asc
| Property | Type | Default | Description |
|---|---|---|---|
field |
string | — | Dimension or measure name from the query's SELECT, any measure or metric of the model, or a numeric position (e.g. "1") |
direction |
enum | asc |
asc or desc |
nulls |
enum | engine default | first or last |
A dimension must appear in the query's select. A numeric string references a returned column by position (1-based).
Sorting by a Measure the Query Does Not Return¶
A measure or metric can be sorted by without being selected: the three customers with the most revenue, showing only their names.
The rows are the query's own. The sort measure is computed in a query of its own over the same dimensions and where filters, joined onto the rows by their dimensions, and sorted on; it is not returned. Selecting it would have changed the rows: a customer without orders is a row of Customer Name alone but not of Customer Name, Revenue. Here that customer keeps the row and sorts as NULL (put such rows last with nulls: last).
Any measure or metric works, cumulative, window and derived ones included. A dimension the query does not select is UNKNOWN_ORDER_BY_FIELD: the query's grain holds no single value of it. Beside ROLLUP / CUBE it is ORDER_BY_COMBINATION_NOT_SUPPORTED, since a subtotal row has no value at the detail grain; select the measure to sort by it there.
Limit¶
Restrict the number of returned rows:
Validation¶
Invalid queries return error responses:
| Error Code | Status | Cause |
|---|---|---|
UNKNOWN_DIMENSION |
400 | Dimension name not in model |
INVALID_TIME_GRAIN |
422 | A dimension's :grain suffix is not one of year, quarter, month, week, day, hour, minute, second |
UNKNOWN_MEASURE |
400 | Measure name not in model |
DUPLICATE_DIMENSION |
422 | A dimension is selected twice at the same grain (Order Date beside Order Date:month when it declares timeGrain: month); one column would be named twice. The same dimension at two grains is two columns and allowed |
DUPLICATE_MEASURE |
422 | A measure or metric is selected twice |
UNKNOWN_FILTER_FIELD |
400 | Filter field is not a dimension (WHERE) or measure (HAVING) |
UNREACHABLE_FILTER_OBJECT |
400 | WHERE filter names a data object the query cannot reach |
FILTER_ADMITS_ROWS_WITHOUT |
400 | WHERE on the many side of the measures' objects could hold for a row with no matching rows there, and the query's shape cannot add those rows (several one-side objects under ROLLUP / CUBE, a nested object, allowFanOut); use exists / nonexists |
FILTER_ON_CONFORMED_OBJECT |
400 | WHERE filter reads a fact an anchored measure conforms together with the anchor's side (an OR across both); see Filters on a conformed fact |
STATIC_FILTER_UNREACHABLE |
400 | A static model filter declared enforce: always names a data object the query, or one measure's fact, cannot reach |
UNKNOWN_ORDER_BY_FIELD |
400 | ORDER BY field is neither a dimension in the query's SELECT nor a measure or metric of the model |
ORDER_BY_COMBINATION_NOT_SUPPORTED |
400 | ORDER BY a measure or metric the query does not select, beside ROLLUP / CUBE |
INVALID_ORDER_BY_POSITION |
400 | Numeric ORDER BY position out of range |
INVALID_FILTER_OPERATOR |
400 | Unrecognized filter operator |
INVALID_RELATIVE_FILTER |
400 | Malformed relative time filter |
UNKNOWN_SUBQUERY_DATA_OBJECT |
400 | exists / nonexists references an unknown target data object |
NO_JOIN_PATH_TO_SUBQUERY |
400 | No join path exists from the filter subject to the subquery target |
UNKNOWN_SUBQUERY_FILTER_COLUMN |
400 | subquery.filter field is neither a column of the target, a dimension, nor a valid DataObject.Column |
UNREACHABLE_SUBQUERY_FILTER_OBJECT |
400 | subquery.filter names a data object not reachable from the target |
SUBQUERY_FILTER_OBJECT_NOT_JOINABLE |
400 | subquery.filter resolves to (or only through) the correlation subject |
UNKNOWN_PATH_NAME |
400 | subquery.pathName does not match any declared secondary join |
AMBIGUOUS_JOIN |
422 | Multiple join paths possible |
DIMENSIONS_EXCLUDE_WITH_MEASURES |
400 | dimensionsExclude used with measures |
DIMENSIONS_EXCLUDE_INSUFFICIENT |
400 | dimensionsExclude with fewer than 2 dimensions |
FILL_REQUIRES_ONE_TIME_DIMENSION |
400 | fill without exactly one time-grained dimension typed date or timestamp, or with it inside a coalesce group |
FILL_GRAIN_NOT_SUPPORTED |
400 | fill over an hour, minute or second grain |
FILL_COMBINATION_NOT_SUPPORTED |
400 | fill with ROLLUP / CUBE, having, a total, a window or period-over-period metric, or a cumulative metric over another time dimension or over a reaggregate metric |
Semantics Summary¶
| Query Element | SQL Equivalent |
|---|---|
select.dimensions |
SELECT + GROUP BY columns |
select.measures |
SELECT aggregate expressions |
where |
WHERE clause |
having |
HAVING clause |
orderBy |
ORDER BY clause |
limit |
LIMIT clause |
dimensionsExclude |
Anti-join via CROSS JOIN + EXCEPT (dimension-only) |