Skip to main content
Clause ordering and optionality
  • Required: FROM · SHOW · (SINCE or DURING)
  • Optional: GROUP BY · WHERE · HAVING · UNTIL · TIMESERIES · SEGMENT BY · COMPARE TO · ORDER BY · WITH · VISUALIZE
  • Canonical order: FROM → SHOW → (GROUP BY / WHERE / SEGMENT BY) → [HAVING] → (SINCE [UNTIL] | DURING) → [TIMESERIES] → [SEGMENT BY] → [COMPARE TO] → [ORDER BY] → [WITH …] → [VISUALIZE]
The parser accepts flexible ordering of WHERE, GROUP BY, and SEGMENT BY clauses before the time bound. SEGMENT BY can also appear after the time bound or TIMESERIES for backwards compatibility. Use either SINCE (with an optional UNTIL) or DURING to bound a query, but not both. DURING is a single-token shortcut for common ranges; SINCE/UNTIL gives you full control over the start and end. Minimal example
Full example

Clauses

FROM

  • Purpose: Selects the dataset.
  • Example:

SHOW

  • Purpose: Lists one or more expressions to compute. Typically uses aggregation functions over metrics or fields. In the report editor, the visual query builder lets you select multiple metrics for the same query; each becomes a separate item in the SHOW list.
  • Examples:

GROUP BY

  • Purpose: Defines the grouping keys for aggregation.
  • Keys: Can be identifiers, dimensions, product_attributes.* paths, or discovered custom.* context paths. See Custom context dimensions.
  • TOP N Modifier: Limit results to the top N values for a dimension.
  • Examples:

TOP N modifier

The TOP N modifier ranks the first grouping dimension by the primary metric (the first SHOW expression), highest first. Other grouping and segmentation dimensions define separate ranking groups. ORDER BY changes the final display order, not which values qualify for TOP N. Three variants are available:
  • TOP N: Shows the top N values plus an “Other” category for the remainder.
  • ONLY TOP N: Shows only the top N values, hiding the remainder entirely.
  • TOP N OVERALL: Ranks values across the full time range rather than per-period when used with a supported TIMESERIES query. It does not enable gap filling.
The Other row sums additive metrics, such as sales totals and counts. Rates, averages, and distinct counts remain blank on that row rather than showing a misleading sum. The retained top rows keep their original metric values. The same rules apply to previous-period values when you use COMPARE TO. For example, this query returns the five products with the highest sales, plus Other, with previous-period values:
TOP N, ONLY TOP N, and TOP N OVERALL cannot be combined with WITH TOTALS, GROUP_TOTALS, PERCENT_CHANGE, or CUMULATIVE_VALUES. COMPARE TO alone is supported, without PERCENT_CHANGE.TOP N also rejects TIMESERIES gap filling for natural granularities: minute, hour, day, week, month, quarter, and year. Gap filling applies when the query has resolved start and end bounds. The report runner can supply those bounds even when you omit UNTIL, so omitting UNTIL does not guarantee a compatible query. Use TOP N without TIMESERIES for a ranked report, or remove TOP N to show a gap-filled time series. OVERALL does not bypass this restriction.

WHERE (optional)

  • Purpose: Filters rows before aggregation using boolean expressions over dimensions, fields, or attributes.
  • Comparison operators: =, !=, <, <=, >, >=
  • Logical operators: AND, OR, NOT
  • Null handling: IS NULL, IS NOT NULL
  • Precedence: Parentheses are supported for grouping conditions.
  • Examples:

HAVING (optional)

  • Purpose: Filters grouped results after aggregation using boolean expressions over metrics. Use it to hide low-volume rows. For example, only show products with at least 500 impressions when ranking by click-through rate.
  • Requires: A GROUP BY or TIMESERIES clause. HAVING is invalid on ungrouped queries.
  • References: Only known metrics from the dataset. Referencing an unknown metric is a validation error.
  • Comparison operators: =, !=, <, <=, >, >=
  • Logical operators: AND, OR, NOT (parentheses supported)
  • Examples:
Metrics referenced only in HAVING do not appear in the result. They are computed as hidden companions so you can filter on volume without adding it as an output column.

SINCE

  • Purpose: Defines the start of the time window for the query.
  • Accepted forms:
    • Relative: -7d, -14d, -30d, -60d, -90d, -180d, -365d, -24h, -48h, -12m, -1y
    • Keywords: today, yesterday, this_week, last_week, this_month, last_month, this_quarter, last_quarter, this_year, last_year
    • Rolling windows: past_7_days, past_14_days, past_30_days, past_60_days, past_90_days, past_180_days, past_365_days
    • Custom rolling window: past_N_days where N is any positive integer (for example, past_45_days, past_120_days)
    • Year-to-date: year_to_date
    • Black Friday / Cyber Monday by year: bfcm2024, bfcm2025 (the four days from Black Friday through Cyber Monday)
    • ISO: 2025-03-15 or 2025-03-15T10:30:00Z (timezone offsets supported, ISO 8601)
  • Examples:

UNTIL (optional)

  • Purpose: Defines the end of the time window for the query. When omitted, the query runs up to the current time.
  • Accepted forms: Same as SINCE (relative offsets, keywords, rolling windows, ISO timestamps).
  • Examples:
The UNTIL point is exclusive: the query counts activity up to, but not including, that moment. For example, SINCE 2024-01-01 UNTIL 2024-12-31 covers January 1 through December 30. To include all of December 31, use UNTIL 2025-01-01.

DURING

  • Purpose: A single-token shortcut for common time ranges. Use DURING instead of SINCE/UNTIL when one of the named ranges fits your query.
  • Accepted forms:
    • Calendar keywords: today, yesterday, this_week, last_week, this_month, last_month, this_quarter, last_quarter, this_year, last_year
    • Rolling windows: past_7_days, past_30_days, past_90_days, past_N_days (any positive integer N)
    • Year-to-date: year_to_date
    • Black Friday / Cyber Monday by year: bfcm2024, bfcm2025
  • Mutually exclusive: A query uses either SINCE (with optional UNTIL) or DURING, never both.
  • Examples:

TIMESERIES (optional)

  • Purpose: Groups results by time intervals with automatic backfilling for missing periods.
  • Granularities:
    • Standard: day, week, month, quarter, year, hour, minute
    • Cyclical: day_of_week, hour_of_day, week_of_year, month_of_year
  • Examples:
When using TIMESERIES, the query results include a time dimension that shows values for each period within the SINCE range. Missing periods are automatically backfilled with zero values, so TIMESERIES output works well for charting and trend analysis. Natural-granularity gap filling is incompatible with TOP N. Remove TOP N when you need a gap-filled time series.

SEGMENT BY (optional)

  • Purpose: Adds a segmentation dimension applied to each group.
  • Accepts: built-in dimensions and discovered custom context dimensions (for example, custom.storefront).
  • Examples:

COMPARE TO (optional)

  • Purpose: Repeats the query over a shifted time window and returns both result sets so you can compare two periods (for example, this month vs. last month). The shifted window has the same length as the primary window.
  • Syntax: COMPARE TO <target>
  • Targets:
    • previous_period — shifts back by the exact length of the primary window (a 7-day window compares against the prior 7 days).
    • previous_month — shifts back by one calendar month.
    • previous_year — shifts back by one calendar year.
    • previous_year_match_day_of_week — shifts back 364 days so the same days of the week align (useful for retail where day-of-week effects matter).
  • Combine with WITH PERCENT_CHANGE to surface the percentage delta between the two periods.
  • Examples:

ORDER BY (optional)

  • Purpose: Sorts the result rows. Without it, results are sorted by the first SHOW expression in descending order.
  • Syntax: ORDER BY <target> [ASC | DESC] [, <target> [ASC | DESC]]*
  • Direction: DESC is the default when omitted. Rows with a NULL value in the sort column always sort last.
  • Targets: A column visible in the result: an AS alias, a metric or expression from the SHOW list, or a dimension used in GROUP BY or SEGMENT BY. Derived columns added by other clauses are also valid: *_previous when COMPARE TO is present, *_pct_change when WITH PERCENT_CHANGE is present, *_cumulative when WITH CUMULATIVE_VALUES and TIMESERIES are present, and *_previous_cumulative when all three are present.
  • Restrictions: Unlike HAVING, ORDER BY cannot reference metrics that are not in the SHOW list, because ordering by a hidden column has no meaning. Handle dimensions (dimensions that resolve a handle to an internal ID, such as sort_order) cannot be sort targets. Unknown or ambiguous targets are validation errors that list the available columns.
  • Examples:
When ordering by a rate (for example, ctr or cvr), add a HAVING volume floor on the underlying count so small denominators don’t dominate the top of the table.

WITH (optional)

  • Purpose: Adds calculated rollups and derived series to the result without changing the base aggregation. Combine modifiers with commas in any order; each modifier may appear at most once.
  • Syntax: WITH <modifier> [, <modifier>]*
  • Modifiers:
    • TOTALS — adds a grand total row across every group.
    • GROUP_TOTALS — adds subtotal rows when a query has both GROUP BY and SEGMENT BY (or TIMESERIES). One subtotal is emitted per primary group.
    • PERCENT_CHANGE — adds a percent-change column. Requires COMPARE TO.
    • CUMULATIVE_VALUES — adds a running total series. Only valid for additive expressions (SUM, COUNT, and add/subtract combinations of them). Non-additive expressions such as AVG, MIN, MAX, COUNT_DISTINCT, and ratios are rejected.
  • Examples:

VISUALIZE (optional)

  • Purpose: Specifies how to render the query results graphically.
  • Syntax: VISUALIZE <target> [TYPE <type>] [BY <field>] [SERIES <field>] [BUCKETS <n>, <n>, ...] [LIMIT <n>] [MAX <number>]
  • Target: The metric or expression to visualize (e.g., SUM(total_sales) or a field name).
  • Options: Each option may appear at most once and they can be written in any order.
    • TYPE <type> — chart type. One of table, bar, line, donut, horizontal_bar, stacked_bar, area, card, geo_bar. Use geo_bar for ranked geographic distributions; country codes in geo_country are rendered as full country names, and bars are sorted in descending order of the metric.
    • BY <field> — primary axis or grouping field for the chart (for example, BY position).
    • SERIES <field> — splits the data into separate series by the given field (for example, SERIES geo_country).
    • BUCKETS <n>, <n>, ... — numeric bucket boundaries for histogram-style charts.
    • LIMIT <n> — caps the number of categories or series rendered.
    • MAX <number> — caps the number of data points displayed.
  • Examples:
Combine VISUALIZE with TIMESERIES to create time-series charts, or with GROUP BY to create bar and donut charts that show distribution across dimensions. Identifiers and paths
  • Identifiers: letters, digits, underscores; start with a letter or underscore.
  • Paths: dot notation (for example, product_attributes.color).
Literals
  • Strings: ‘value’ or “value”
  • Numbers: 10, 10.5
  • Booleans: TRUE, FALSE

Arithmetic expressions

LayersQL supports arithmetic operations in both SHOW and WHERE clauses, so you can create calculated metrics and multi-part filtering conditions.

Supported operators

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulo: %
  • Unary minus: - (negation)

Operator precedence

Arithmetic expressions follow standard mathematical precedence: multiplication, division, and modulo are evaluated before addition and subtraction. Use parentheses to override the default precedence.

Examples

Blend sales and units into a weighted score for a sort order:
Divide one aggregation by another to get the average selling price per unit:
Use parentheses and a number to turn a ratio into a percentage:
When a divisor is zero (for example, a product with views but no units sold), the result is empty rather than an error.

Aliasing arithmetic expressions

Use the AS keyword to give your calculated expressions meaningful names. You can compute several named expressions in one query:

Examples

Group by attributes with a rolling window
Filter by geography and marketing channel
Calculate weighted metrics with segmentation