Reten Docs

Generate SQL

Compiles an audience criteria definition to BigQuery SQL, from the request body (not yet persisted) or by id of a saved criterion, in parameterized or literal format.

Generate SQL

Compiles an audience criteria definition to BigQuery SQL (GoogleSQL). A single engine serves two entry points:

  • POST /api/audience-criterias/generate-sql — compiles a definition sent in the body (not yet persisted).
  • GET /api/audience-criterias/:id/sql — compiles an already saved criterion, referenced by its id.

Both return the same response shape: IAudienceCriteriaSql, a discriminated union on the format field. The format (parameterized or literal) is chosen per request and governs both the shape of the query and the fields of the response.

Within a project, the SQL of every audience other than the root audience comes out intersected with the project's root audience — see Intersection with the root audience.

Auth: Required — audience-criteria:view-sql permission (both endpoints).

The generated SQL is meant for BigQuery: it references tables as `<gcp-project>.<dataset>.<table>`. The query is an intersectable chain of CTEs — without the leading WITH and without a trailing SELECT — so a consumer can splice it straight into its own WITH … SELECT. The last CTE is named finalCteName (CTE_AUDIENCE_USERS) and exposes the identity column subjectColumn (e.g. user_id). In the parameterized format it uses named @pN parameters. The <gcp-project> (the Google Cloud project, not a Reten project) comes from the API's environment configuration and the <dataset> is resolved from the tenant; neither is part of the input contract.


POST /api/audience-criterias/generate-sql

Compiles a definition sent in the body, without persisting it.

Auth: Required — audience-criteria:view-sql permission

The endpoint responds 201 Created —not 200—, even though it does not create any resource.

Request Body

Root level (GenerateSqlDto): the criterion definition (CriteriaDefinitionDto) plus the format field.

FieldTypeRequiredDescription
queryBlocksQueryBlockDto[]YesMinimum 1 element. Each block ≈ a complete SQL statement.
composedWithCreateCompositionDto[]NoComposes this definition with other audiences via set operations.
format"parameterized" | "literal"NoOutput format. Default parameterized (see Output format).
criteriaIdstring (UUID) | nullNoThe saved audience this definition edits, so the draft gives the same SQL that audience will give once saved (see Intersection with the root audience). Absent or null: a new audience. It must be a valid UUID (otherwise, 400) of an audience of the active project (otherwise, 404).

Unlike Create, the definition does not carry name or description: it is only the query tree. Validation is strict, so sending name/description (or any other unknown property) produces a 400.

Criterion Definition

It is the same tree that Create receives, without the name/description fields. It is documented here in a self-contained way.

queryBlocks[] — query block

Each element of queryBlocks (QueryBlockDto) is a complete SQL statement:

FieldTypeRequiredDescription
ordernumber (integer)YesBlock position; integer ≥ 0.
setOperatorSetOperatorEnumNoCombines this block with the previous one. Absent in the first block; required in the rest (see rules).
fromFromDtoYesData source: main table + joins.
selectSelectDtoYesProjection (columns and/or aggregations).
timeWindowTimeWindowDtoNoBlock time window (discriminated union on timeOperator).
whereWhereDtoYesPredicate tree. Required even if it is an empty group.
groupByColumnRefDto[]NoGrouping columns.
havingHavingDtoNoFilter on aggregates.

The setOperator of a query block combines blocks within the same definition; it should not be confused with the setOperator of a composition, which combines whole criteria. They are two distinct levels of set operation.

ColumnRefDto — column reference

Used throughout the tree (select, filters, group by, joins, aggregates, time window):

FieldTypeRequiredDescription
tablestringYesCatalog table. Not empty.
columnstringYesColumn. Not empty. Can be a STRUCT path (e.g. "pricing.final_amount").

Every column is always qualified with its table to avoid ambiguity.

from — data source (FromDto)
FieldTypeRequiredDescription
tablestringYesMain catalog table. Not empty.
joinsJoinDto[]NoJoins with other tables. Default [].
unnestsColumnRefDto[]NoRepeated columns declared as a row source (one row per element). An audience does not accept them: omit the field or send [] (the default); a non-empty list gives 400.

Each JoinDto:

FieldTypeRequiredDescription
typeJoinTypeEnumYesINNER | LEFT | RIGHT | FULL.
tablestringYesTable to join (from the catalog). Not empty.
onJoinPredicateDto[]YesJoin conditions.

Each JoinPredicateDto is a pair of columns: { left: ColumnRefDto, right: ColumnRefDto }.

select — projection (SelectDto)
FieldTypeRequiredDescription
distinctbooleanYesApplies SELECT DISTINCT.
items(SelectColumnItem | SelectAggregateItem)[]YesNot empty. Discriminated union on the kind field.

The items are discriminated by kind:

  • Column — kind: "column":

    FieldTypeRequiredDescription
    kind"column"YesDiscriminator.
    columnColumnRefDtoYesProjected column.
    aliasstringNoMust match ^[A-Za-z_][A-Za-z0-9_]*$.
  • Aggregate — kind: "aggregate":

    FieldTypeRequiredDescription
    kind"aggregate"YesDiscriminator.
    aggregateAggregateDtoYesAggregation expression.
    aliasstringYesHere the alias is required. Same identifier regex.

AggregateDto:

FieldTypeRequiredDescription
aggregationOperatorAggregationOperatorEnumYesCOUNT | SUM | AVG | MIN | MAX.
operandobjectYesWhat is aggregated. Discriminated union on kind: column, star or arithmetic (see below).
distinctbooleanNoApplies DISTINCT inside the aggregate.

operand — what is aggregated — is discriminated by kind:

kindAdditional fieldsMeaning
columncolumn: ColumnRefDtoA catalog column.
star(none)*: counts rows. Only valid with COUNT and without distinct (COUNT(DISTINCT *) is not allowed).
arithmeticarithmeticOperator: ArithmeticOperatorEnum, left, rightBinary expression. Each side is another operand: a column or a nested arithmetic (never star).

ArithmeticOperatorEnum: ADD | SUBTRACT | MULTIPLY | SAFE_DIVIDE (a division that yields NULL when the denominator is zero instead of failing the query). The columns of an arithmetic expression must be numeric (INT64, NUMERIC, BIGNUMERIC, FLOAT64), and expressions nest up to 3 levels of arithmetic, counting the outermost one.

where — predicate tree (WhereDto)

The where is a recursive tree. The root node is always a group, and its leaves come in two kinds:

kindWhat it filters
groupNot a leaf: it groups children with AND / OR. Groups can be nested.
predicateA scalar column of a table in the from.
recordPredicateA RECORD REPEATED column: at least 1 element satisfies the sub-filter.
Group — kind: "group"
FieldTypeRequiredDescription
kind"group"YesDiscriminator.
logicalOperatorLogicalOperatorEnum (AND | OR)YesConnective between the children.
children(Group | Leaf)[]YesGroup children; they can be nested groups.

logicalOperator is always required in a group, but only takes effect with 2 or more children. With fewer than 2 children its value is irrelevant (generates the same SQL), but it must be sent anyway. A where without filters is expressed as an empty group: { "kind": "group", "logicalOperator": "AND", "children": [] }.

Column leaf — kind: "predicate"

Compares a scalar column qualified by its table.

FieldTypeRequiredDescription
kind"predicate"YesDiscriminator.
columnColumnRefDtoYesPredicate column.
comparisonOperatorComparisonOperatorEnumYesComparison operator.
valuePredicateValueDependsIts shape depends on the operator.
{
  "kind": "predicate",
  "column": { "table": "user_properties", "column": "country" },
  "comparisonOperator": "IN",
  "value": ["CL", "MX"]
}
Record leaf — kind: "recordPredicate"

Filters by a RECORD REPEATED column (an array of structs, such as attributes). It means at least one element of the array satisfies the sub-filter.

FieldTypeRequiredDescription
kind"recordPredicate"YesDiscriminator.
columnColumnRefDtoYesRECORD REPEATED column of a table in the from.
subWhereRelative sub-treeYesConditions over the element's sub-fields. It cannot be left empty.
{
  "kind": "recordPredicate",
  "column": { "table": "event_transactions", "column": "attributes" },
  "subWhere": {
    "kind": "group",
    "logicalOperator": "AND",
    "children": [
      { "kind": "predicate", "field": "key", "comparisonOperator": "EQUALS", "value": "canal" },
      { "kind": "predicate", "field": "value", "comparisonOperator": "EQUALS", "value": "web" }
    ]
  }
}

The subWhere conditions are evaluated over a single element of the array, not over the whole array. The example above selects rows that have an attribute whose key is canal and whose value is web — not rows that have an attribute with that key and another, different one, with that value.

Which columns accept a record filter is stated by the catalog: the ones that come with kind: "record".

Relative sub-tree

The subWhere is an AND/OR group whose leaves are resolved against the sub-fields the record declares.

There is a single difference with the top-level tree, and it is the most common source of errors:

Inside a relative sub-tree the operands carry no table: you write "field": "key", not "column": { "table": "attributes", "column": "key" }. The leaf uses the field key (a string), not column.

Leaves allowed inside a relative sub-tree:

  • Scalar leaf — { "kind": "predicate", "field": string, "comparisonOperator": …, "value"?: … }. The field must be a scalar sub-field of the record.
  • Nested record — { "kind": "recordPredicate", "field": string, "subWhere": … }. A record inside another record; it nests with no declared limit, as long as the catalog declares each level.
  • Group — the same group shape, to combine the previous leaves with AND/OR.
value shape by comparisonOperator
Operatorsvalue shapeExample
IS_NULL, IS_NOT_NULLNo value (omitted)(omitted)
IN, NOT_INNon-empty list ScalarValue[]["CL", "MX"]
BETWEENPair [min, max][10, 20]
The rest (EQUALS, NOT_EQUALS, GREATER_THAN, LESS_THAN, GREATER_THAN_OR_EQUAL, LESS_THAN_OR_EQUAL, CONTAINS, NOT_CONTAINS, STARTS_WITH, ENDS_WITH)Single scalar"active" · 42

ScalarValue = string | number | boolean. In addition, each operator must be compatible with the column's type (see validation rules).

groupBy — grouping columns

Optional list of ColumnRefDto[]. When the block aggregates (declares groupBy or has an aggregate in the select), the groupBy must match exactly the non-aggregated columns of the select (see validation rules).

having — filter on aggregates (HavingDto)

Same recursive structure as where (nested AND/OR groups and the same value rule per operator), but the leaf operates on an aggregate, not on a column:

  • Predicate (leaf) — { kind: "predicate", aggregate: AggregateDto, comparisonOperator: ComparisonOperatorEnum, value?: PredicateValue }.
  • Group — identical to the one in where.
timeWindow — time window (TimeWindowDto)

Discriminated union on timeOperator. Narrows the block to a time period over a TIMESTAMP column from the catalog (reference). It is a sibling field of where, not a node of the filter tree.

timeOperatorAdditional fields
ALL_TIME(none) — not bounded by time.
IN_THE_LASTreference: ColumnRefDto, unit: TimeUnitEnum, value: integer > 0
IN_THE_FIRSTreference: ColumnRefDto, unit: TimeUnitEnum, value: integer > 0
SINCEreference: ColumnRefDto, from: string (YYYY-MM-DD)
BETWEENreference: ColumnRefDto, from: string (YYYY-MM-DD), to: string (YYYY-MM-DD)

TimeUnitEnum: DAYS | WEEKS | MONTHS | YEARS.

Business semantics of each operator:

  • ALL_TIME — no window; considers the entire history.
  • IN_THE_LAST — rolling window relative to "now": the last value unit (e.g. last 30 DAYS). Recomputed on each run.
  • IN_THE_FIRST — window relative to the origin of the user's lifecycle (their signup date): the first value unit of each user's life. Anchored per user, not to a fixed date.
  • SINCE — from the civil date from (inclusive) onward.
  • BETWEEN — between from and to, both civil dates inclusive of their full day.

The civil dates YYYY-MM-DD (SINCE, BETWEEN) are resolved to the start of the day in the tenant's time zone. The time-zone detail is internal; sending the civil date is enough.

composedWith[] — composition with other audiences

Each element (CreateCompositionDto) combines this definition with another audience via a set operation:

FieldTypeRequiredDescription
operandCriteriaIdstring (UUID)YesId of the other audience (operand). Must exist.
setOperatorSetOperatorEnumYesUNION_DISTINCT | UNION_ALL | INTERSECT_DISTINCT.

Example

Definition of an audience of users with a transaction within their first 30 days since signup (IN_THE_FIRST). By omitting format, the response is parameterized (default).

curl -X POST https://api.reten.ai/api/audience-criterias/generate-sql \
  -H "Authorization: Bearer <token>" \
  -H "x-tenant-id: <tenant-id>" \
  -H "x-project-id: <project-id>" \
  -H "Content-Type: application/json" \
  -d '{
    "queryBlocks": [
      {
        "order": 0,
        "from": { "table": "event_transactions" },
        "select": {
          "distinct": true,
          "items": [
            {
              "kind": "column",
              "column": { "table": "event_transactions", "column": "user_id" }
            }
          ]
        },
        "timeWindow": {
          "timeOperator": "IN_THE_FIRST",
          "reference": { "table": "event_transactions", "column": "event_date" },
          "unit": "DAYS",
          "value": 30
        },
        "where": { "kind": "group", "logicalOperator": "AND", "children": [] }
      }
    ]
  }'
import axios from 'axios';

const body = {
  queryBlocks: [
    {
      order: 0,
      from: { table: 'event_transactions' },
      select: {
        distinct: true,
        items: [
          {
            kind: 'column',
            column: { table: 'event_transactions', column: 'user_id' },
          },
        ],
      },
      timeWindow: {
        timeOperator: 'IN_THE_FIRST',
        reference: { table: 'event_transactions', column: 'event_date' },
        unit: 'DAYS',
        value: 30,
      },
      where: { kind: 'group', logicalOperator: 'AND', children: [] },
    },
  ],
  // format: 'literal',  // optional; defaults to 'parameterized'
};

const response = await axios.post(
  'https://api.reten.ai/api/audience-criterias/generate-sql',
  body,
  { headers: { Authorization: 'Bearer <token>', 'x-tenant-id': '<tenant-id>', 'x-project-id': '<project-id>' } },
);
const sql = response.data; // IAudienceCriteriaSql

The response is documented in IAudienceCriteriaSql, with an example of each format.


GET /api/audience-criterias/:id/sql

Compiles an already saved criterion, referenced by its id. The definition does not travel in the body: it is taken from the criterion persisted in the active project.

Auth: Required — audience-criteria:view-sql permission

Status 200 OK (it is a GET).

Path Parameters

ParameterTypeRequiredDescription
idUUIDYesId of the audience criteria. Must be a valid UUID (otherwise, 400).

Query Parameters

GetSqlDto:

ParameterTypeRequiredDescription
format"parameterized" | "literal"NoOutput format. Default parameterized (see Output format).

Example

curl "https://api.reten.ai/api/audience-criterias/f47ac10b-58cc-4372-a567-0e02b2c3d479/sql?format=literal" \
  -H "Authorization: Bearer <token>" \
  -H "x-tenant-id: <tenant-id>" \
  -H "x-project-id: <project-id>"
import axios from 'axios';

const id = 'f47ac10b-58cc-4372-a567-0e02b2c3d479';
const response = await axios.get(
  `https://api.reten.ai/api/audience-criterias/${id}/sql`,
  {
    params: { format: 'literal' }, // optional; defaults to 'parameterized'
    headers: { Authorization: 'Bearer <token>', 'x-tenant-id': '<tenant-id>', 'x-project-id': '<project-id>' },
  },
);
const sql = response.data; // IAudienceCriteriaSql

Output format — format

The format field decides how the SQL values are emitted and which fields the response carries. It is optional; if omitted, the effective value is parameterized.

formatHow it emits valuesExtra fields in the response
parameterizedNamed @pN placeholders in the query; the binding goes separately.params, types
literalValues are inlined as safe literals inside the query.(none)
  • In generate-sql (POST) the format goes in the body.
  • In :id/sql (GET) the format goes as a query param.

Only the strings "parameterized" and "literal" are accepted; any other value produces a 400.

Response — IAudienceCriteriaSql

It is a discriminated union on format. Both variants share a base and differ in the binding fields.

Base (common to both formats):

FieldTypeDescription
querystringAn intersectable chain of CTEs (single string, clauses separated by \n): without the leading WITH and without a trailing SELECT, so it can be spliced into a WITH … SELECT.
finalCteNamestringName of the final CTE of the chain (stable: CTE_AUDIENCE_USERS); the "handle" of the audience result — a consumer does JOIN {finalCteName} / SELECT … FROM {finalCteName}.
subjectColumnstringIdentity column exposed by the final CTE (e.g. user_id).
granularity"table_row" | "record_element"What one row of the final CTE is. In an audience it is always table_row: one row per table row, one per user. The contract's other value, record_element (one row per element of a repeated record declared as a row source), does not occur in audiences, which do not accept row sources.
  • format: "parameterized" — IParameterizedAudienceCriteriaSql:

    FieldTypeDescription
    format"parameterized"Discriminator.
    querystringCTE chain with @pN placeholders.
    finalCteNamestringName of the final CTE.
    subjectColumnstringIdentity column exposed by the final CTE.
    granularity"table_row" | "record_element"What one row of the final CTE is (in an audience, always table_row).
    paramsRecord<string, ScalarValue>Binding of each @pN → its value. ScalarValue = string | number | boolean.
    typesRecord<string, string>BigQuery parameter type of each @pN (e.g. STRING, INT64, TIMESTAMP, BOOL, FLOAT64, NUMERIC, BIGNUMERIC).
  • format: "literal" — ILiteralAudienceCriteriaSql:

    FieldTypeDescription
    format"literal"Discriminator.
    querystringCTE chain with the values already inlined as literals.
    finalCteNamestringName of the final CTE.
    subjectColumnstringIdentity column exposed by the final CTE.
    granularity"table_row" | "record_element"What one row of the final CTE is (in an audience, always table_row).

In parameterized, params and types are part of the contract: the query carries @pN and is not executable without its binding and its types. In literal there is no binding —the values live inside the query— so it does not carry params or types. Always discriminate by format before reading params/types.

Example — parameterized (default)

201 response to the example POST above (without format):

{
  "format": "parameterized",
  "query": "op_5e2a91c07b3d_0 AS (\nSELECT DISTINCT `event_transactions`.`user_id`\nFROM `reten-prod.tenant_a1b2c3d4.event_transactions` AS event_transactions\nINNER JOIN `reten-prod.tenant_a1b2c3d4.user_properties` AS user_properties ON `event_transactions`.`user_id` = `user_properties`.`user_id`\nWHERE `event_transactions`.`event_date` BETWEEN `user_properties`.`sign_up_date` AND TIMESTAMP(DATETIME_ADD(DATETIME(`user_properties`.`sign_up_date`), INTERVAL @p0 DAY))\n),\nop_9a8b7c6d5e4f_0 AS (\nSELECT DISTINCT `user_properties`.`user_id`\nFROM `reten-prod.tenant_a1b2c3d4.user_properties` AS user_properties\nWHERE `user_properties`.`is_active` = @p1\n),\nCTE_AUDIENCE_USERS AS (\nSELECT * FROM op_5e2a91c07b3d_0\nINTERSECT DISTINCT\nSELECT * FROM op_9a8b7c6d5e4f_0\n)",
  "finalCteName": "CTE_AUDIENCE_USERS",
  "subjectColumn": "user_id",
  "granularity": "table_row",
  "params": { "p0": 30, "p1": true },
  "types": { "p0": "INT64", "p1": "BOOL" }
}

The query is a single string with \n line breaks — a CTE chain without the leading WITH and without a trailing SELECT. Formatted for readability:

op_5e2a91c07b3d_0 AS (
SELECT DISTINCT `event_transactions`.`user_id`
FROM `reten-prod.tenant_a1b2c3d4.event_transactions` AS event_transactions
INNER JOIN `reten-prod.tenant_a1b2c3d4.user_properties` AS user_properties ON `event_transactions`.`user_id` = `user_properties`.`user_id`
WHERE `event_transactions`.`event_date` BETWEEN `user_properties`.`sign_up_date` AND TIMESTAMP(DATETIME_ADD(DATETIME(`user_properties`.`sign_up_date`), INTERVAL @p0 DAY))
),
op_9a8b7c6d5e4f_0 AS (
SELECT DISTINCT `user_properties`.`user_id`
FROM `reten-prod.tenant_a1b2c3d4.user_properties` AS user_properties
WHERE `user_properties`.`is_active` = @p1
),
CTE_AUDIENCE_USERS AS (
SELECT * FROM op_5e2a91c07b3d_0
INTERSECT DISTINCT
SELECT * FROM op_9a8b7c6d5e4f_0
)

Each @pN is bound with params[pN] (its value) and types[pN] (its BigQuery type); without that binding the query is not executable. p0 belongs to the audience and p1 to the project's root audience, which here keeps its default definition (see Intersection with the root audience). The INNER JOIN to user_properties is not in the request: IN_THE_FIRST measures each user's first days from their signup date, so the API adds it.

To run it stand-alone, wrap the chain with the CTE name from the response: WITH {query} SELECT * FROM {finalCteName}. To intersect it against another query, splice {query} into your own WITH and JOIN {finalCteName} on {subjectColumn}.

Example — literal

The same definition with format: "literal" (in the by-id variant, ?format=literal):

{
  "format": "literal",
  "query": "op_5e2a91c07b3d_0 AS (\nSELECT DISTINCT `event_transactions`.`user_id`\nFROM `reten-prod.tenant_a1b2c3d4.event_transactions` AS event_transactions\nINNER JOIN `reten-prod.tenant_a1b2c3d4.user_properties` AS user_properties ON `event_transactions`.`user_id` = `user_properties`.`user_id`\nWHERE `event_transactions`.`event_date` BETWEEN `user_properties`.`sign_up_date` AND TIMESTAMP(DATETIME_ADD(DATETIME(`user_properties`.`sign_up_date`), INTERVAL 30 DAY))\n),\nop_9a8b7c6d5e4f_0 AS (\nSELECT DISTINCT `user_properties`.`user_id`\nFROM `reten-prod.tenant_a1b2c3d4.user_properties` AS user_properties\nWHERE `user_properties`.`is_active` = TRUE\n),\nCTE_AUDIENCE_USERS AS (\nSELECT * FROM op_5e2a91c07b3d_0\nINTERSECT DISTINCT\nSELECT * FROM op_9a8b7c6d5e4f_0\n)",
  "finalCteName": "CTE_AUDIENCE_USERS",
  "subjectColumn": "user_id",
  "granularity": "table_row"
}

Formatted for readability:

op_5e2a91c07b3d_0 AS (
SELECT DISTINCT `event_transactions`.`user_id`
FROM `reten-prod.tenant_a1b2c3d4.event_transactions` AS event_transactions
INNER JOIN `reten-prod.tenant_a1b2c3d4.user_properties` AS user_properties ON `event_transactions`.`user_id` = `user_properties`.`user_id`
WHERE `event_transactions`.`event_date` BETWEEN `user_properties`.`sign_up_date` AND TIMESTAMP(DATETIME_ADD(DATETIME(`user_properties`.`sign_up_date`), INTERVAL 30 DAY))
),
op_9a8b7c6d5e4f_0 AS (
SELECT DISTINCT `user_properties`.`user_id`
FROM `reten-prod.tenant_a1b2c3d4.user_properties` AS user_properties
WHERE `user_properties`.`is_active` = TRUE
),
CTE_AUDIENCE_USERS AS (
SELECT * FROM op_5e2a91c07b3d_0
INTERSECT DISTINCT
SELECT * FROM op_9a8b7c6d5e4f_0
)

The values are inlined as safe literals (here 30 and TRUE; strings go escaped, in single quotes); there are no params or types.

Intersection with the root audience

Every project has a root audience, and every other audience of the project is evaluated within it. On both endpoints, the SQL of any audience that is not the root audience comes out intersected with the project's root audience:

  • The audience and the root audience keep their own CTEs, and the final CTE intersects the last CTE of each: CTE_AUDIENCE_USERS AS (SELECT * FROM <audience CTE> INTERSECT DISTINCT SELECT * FROM <root audience CTE>).
  • In the parameterized format, the audience's @pN parameters come first and the root audience's parameters follow.
  • There is no intersection when the compiled audience is the root audience itself — GET /:id/sql with the root audience's id, or a draft whose criteriaId is the root audience.
  • The intersection is positional (SELECT * on both sides): the audience must project the same columns as the root audience, in the same order and with compatible types — with the root audience's default definition, only user_id. Otherwise, the SQL fails when it runs.

The intermediate CTEs carry a prefix of each audience's id in their names (for a draft sent without criteriaId, that prefix changes on every request), so always reference the result through finalCteName.

For example, an audience of users with a COMPLETED transaction, in a project whose root audience was edited to country = 'CL' (literal format, formatted for readability):

op_f47ac10b58cc_0 AS (
SELECT DISTINCT `event_transactions`.`user_id`
FROM `<gcp-project>.<dataset>.event_transactions` AS event_transactions
WHERE `event_transactions`.`status` = 'COMPLETED'
),
op_9a8b7c6d5e4f_0 AS (
SELECT DISTINCT `user_properties`.`user_id`
FROM `<gcp-project>.<dataset>.user_properties` AS user_properties
WHERE `user_properties`.`country` = 'CL'
),
CTE_AUDIENCE_USERS AS (
SELECT * FROM op_f47ac10b58cc_0
INTERSECT DISTINCT
SELECT * FROM op_9a8b7c6d5e4f_0
)

Validation Rules

Before compiling, the definition goes through the same two layers of validation as Create, and both return 400 Bad Request:

  1. DTO validation (structure, types, enums, required fields, valid format). message is an array of strings and unknown properties are rejected (including name/description).
  2. Business validation (the definition must generate valid SQL coherent against the catalog). message is a single string with the violated rule.

Business validation runs on both endpoints: generate-sql validates the body definition, and :id/sql validates the saved criterion before compiling it. The full catalog of rules and their exact messages is in Create → Validation Rules.

Error Responses

StatusDescription
400Invalid DTO (missing field, wrong type, enum out of range, invalid format, unknown property such as name/description) or a violated business rule. In :id/sql, also if the id is not a valid UUID; in generate-sql, if the criteriaId is not.
401Missing or invalid Authorization: Bearer.
403The user does not have the audience-criteria:view-sql permission, or the x-tenant-id is not authorized.
404In :id/sql, no audience criteria with that id exists in the active project. In generate-sql, an operandCriteriaId from composedWith or the criteriaId does not exist in the active project.