The SELECT statement retrieves rows from tables in the Chalk catalog, from configured data sources, and from table-valued functions. Use a query as input to CREATE TABLE ... AS SELECT or INSERT INTO to write its rows to a connected table, or to COPY ... TO to export them to files.

​
Examples

-- Select all columns from a data source table
SELECT
  *
FROM
  "my_postgres.public.users";


-- Aggregate transactions per merchant
SELECT
  merchant_id,
  count(*) AS txn_count,
  sum(amount) AS total
FROM
  "my_bigquery.my_dataset.transactions"
GROUP BY
  merchant_id
ORDER BY
  total DESC
LIMIT
  10;


-- Join tables that live in different data sources
SELECT
  u.user_id,
  sum(t.amount) AS user_spending
FROM
  "my_postgres.public.users" u
  LEFT JOIN "my_bigquery.my_dataset.transactions" t ON u.user_id = t.user_id
GROUP BY
  u.user_id;


-- Use a CTE and a window function to pick each user's latest transaction
WITH
  ranked AS (
    SELECT
      user_id,
      amount,
      row_number() OVER (
        PARTITION BY
          user_id
        ORDER BY
          created_at DESC
      ) AS rn
    FROM
      "my_bigquery.my_dataset.transactions"
  )
SELECT
  user_id,
  amount
FROM
  ranked
WHERE
  rn = 1;


-- Query historical feature values from the offline store
SELECT
  pkey,
  value,
  observed_at
FROM
  "chalk.historical_values.user.account_balance"
WHERE
  observed_at > TIMESTAMP '2026-08-25 00:00:00';

​
Syntax

syntax
[ WITH [ RECURSIVE ] <cte> [, ...] ]
SELECT [ DISTINCT [ ON ( <expression> [, ...] ) ] ] <select_item> [, ...]
[ FROM <source> [, ...] ]
[ WHERE <condition> ]
[ GROUP BY <expression> [, ...] ]
[ HAVING <condition> ]
[ QUALIFY <condition> ]
[ ORDER BY { <sort_key> [, ...] | ALL } ]
[ LIMIT <count> ]
[ OFFSET <count> ];

A source can include joins. See also set operations for combining queries and LIMIT and OFFSET for clause order.

​
WITH clause

Common table expressions (CTEs) name a subquery so it can be referenced like a table in the rest of the statement. CTEs may reference earlier CTEs in the same WITH list. Each <cte> has this form.

syntax
<name> [ ( <column_alias> [, ...] ) ] AS ( <select_statement> )
WITH
  spend (user_id, total) AS (
    SELECT
      user_id,
      sum(amount)
    FROM
      "my_bigquery.my_dataset.transactions"
    GROUP BY
      user_id
  )
SELECT
  u.user_id,
  s.total
FROM
  "my_postgres.public.users" u
  JOIN spend s ON u.user_id = s.user_id;

MATERIALIZED CTEs are not currently supported.

​
Recursive CTEs

WITH RECURSIVE defines a CTE as an anchor query combined with a recursive term that references the CTE itself. The anchor runs once. The recursive term then runs repeatedly, each time over the rows the previous round added, until a round adds no rows. The CTE’s result is every row produced along the way.

-- Integers 1 through 5
WITH RECURSIVE
  counter (n) AS (
    SELECT
      1
    UNION ALL
    SELECT
      n + 1
    FROM
      counter
    WHERE
      n < 5
  )
SELECT
  n
FROM
  counter;

With UNION ALL every row is kept. With UNION, a row that the CTE has already produced is dropped, so recursion over cyclic data still terminates. The CTE’s columns take their names and types from the anchor; the recursive term’s rows are cast to those types.

Restrictions:

  • The recursive term may reference its own CTE but not an enclosing recursive CTE.
  • USING KEY is not supported.
  • Recursion that has not stopped after 10,000 rounds fails the query.

​
SELECT list

Each <select_item> can be a supported expression or function call.

syntax
< expression > [[AS] < alias >]

You can reference an earlier alias in a later expression in the same SELECT list (a lateral column alias).

SELECT
  amount * 100 AS cents,
  cents / 3 AS thirds
FROM
  "my_bigquery.my_dataset.transactions";

DISTINCT deduplicates the result rows, and DISTINCT ON (expressions) keeps one row per distinct value of the given expressions:

-- One row per user
SELECT DISTINCT
  ON (user_id) user_id,
  amount
FROM
  "my_bigquery.my_dataset.transactions"
ORDER BY
  user_id,
  created_at DESC;

The star expression * selects all columns of the source, and t.* selects the columns of one source in a join. Both accept DuckDB’s modifiers:

-- Cast one column; it keeps its name and position
SELECT
  * REPLACE(CAST(amount AS BIGINT) AS amount)
FROM
  "my_bigquery.my_dataset.transactions";


-- Drop columns
SELECT
  * EXCLUDE (country, YEAR)
FROM
  "my_bigquery.my_dataset.transactions";


-- Rename a column in place
SELECT
  *
RENAME (created_at AS ts)
FROM
  "my_bigquery.my_dataset.transactions";

COLUMNS(...) selects columns by a regular expression, a list of names, or a lambda over the column name, and applies the surrounding expression to each one. Every result column keeps the name of the column it came from:

-- Cast every column whose name matches the regex
SELECT
  COLUMNS ('amount|year')::BIGINT
FROM
  "my_bigquery.my_dataset.transactions";


SELECT
  max(COLUMNS (['amount', 'created_at']))
FROM
  "my_bigquery.my_dataset.transactions";


SELECT
  COLUMNS (c -> c LIKE '%_id')
FROM
  "my_bigquery.my_dataset.transactions";

* LIKE 'pattern' and * SIMILAR TO 'regex' filter columns by name. A COLUMNS lambda supports LIKE/ILIKE, SIMILAR TO, regexp_matches, contains, starts_with, ends_with, lower/upper, =, <>, IN, IS [NOT] NULL, AND, OR, and NOT. BigQuery’s * EXCEPT (...) is not supported; use EXCLUDE.

Restrictions:

  • SELECT * cannot be combined with GROUP BY or aggregate functions; list the grouped columns explicitly instead.
  • A bare * cannot appear inside another expression (e.g. count(*) is supported, but * + 1 is not); use COLUMNS(*) + 1 instead.

​
FROM clause

The FROM clause names the sources rows are read from. A source can be:

  • A catalog or data source table, referenced with a fully qualified name such as my_postgres.public.users, chalk.online_store.keys, or chalk.historical_values.user. Quote individual identifiers when required. See Chalk SQL catalogs.

  • A table-valued function, such as read_parquet(...), query_values_from_operation_ids(...), or get_dataset_givens(...). For the full list, query "chalk.information_schema.functions" where is_table_valued.

  • A subquery, wrapped in parentheses and optionally aliased.

  • A VALUES list, for inline literal rows:

    SELECT
      *
    FROM
      (
        VALUES
          (1, 'ada'),
          (2, 'grace')
      ) AS t (id, name);
  • A file path or glob, which reads files directly:

    SELECT
      *
    FROM
      's3://my-bucket/events/*.parquet';

A SELECT without a FROM clause evaluates its expressions over a single row (SELECT 1 + 1).

​
TABLESAMPLE

File-backed scans (direct file paths and read_parquet(...)) support percentage-based sampling with the SYSTEM and BERNOULLI methods:

SELECT
  *
FROM
  's3://my-bucket/events/*.parquet' TABLESAMPLE SYSTEM (10 PERCENT);

Not currently supported: sampling catalog or data source tables, RESERVOIR sampling, absolute row-count samples, sampling subqueries or joins, and the USING SAMPLE clause.

​
JOIN clause

Chalk SQL supports joining tables, including tables that live in different data sources, with the following join types:

  • [INNER] JOIN
  • LEFT [OUTER] JOIN
  • RIGHT [OUTER] JOIN
  • FULL [OUTER] JOIN
  • CROSS JOIN
  • ASOF JOIN and ASOF LEFT JOIN, for matching each row to the nearest preceding row by an inequality condition (commonly a timestamp)

Append a join to a source using one of these forms. For <join_type>, use one of the modifiers listed above, such as LEFT OUTER or ASOF LEFT. A bare JOIN is an inner join.

syntax
[ <join_type> ] JOIN <source> { ON <condition> | USING ( <column> [, ...] ) }
CROSS JOIN <source>

Inner joins also accept non-equality ON conditions.

-- Match each transaction to the feature value observed at or before it
SELECT
  t.user_id,
  t.amount,
  f.value AS balance_at_txn
FROM
  "my_bigquery.my_dataset.transactions" t ASOF
  LEFT JOIN "chalk.historical_values.user.account_balance" f ON t.user_id = f.pkey
  AND t.created_at >= f.observed_at;

Not currently supported: NATURAL joins, POSITIONAL joins, and SEMI/ANTI joins.

​
WHERE clause

Filters rows with any supported boolean expression, including subqueries with IN and EXISTS. Where possible, Chalk SQL pushes filters down into the underlying data source so that less data is scanned; pushdown is best-effort and does not change results.

SELECT
  *
FROM
  "my_postgres.public.users"
WHERE
  signup_date > DATE '2026-01-01'
  AND country IN ('US', 'CA');

​
GROUP BY clause

Groups rows by one or more expressions for use with aggregate functions. HAVING filters the grouped rows and requires a GROUP BY clause or an aggregate in the SELECT list.

SELECT
  date_trunc('day', created_at) AS DAY,
  count(*) AS txns
FROM
  "my_bigquery.my_dataset.transactions"
GROUP BY
  date_trunc('day', created_at)
HAVING
  count(*) > 100;

GROUPING SETS, ROLLUP, and CUBE are supported for aggregating across several groupings in one query:

-- Per-country counts plus a grand-total row (country IS NULL)
SELECT
  country,
  count(*)
FROM
  "my_bigquery.my_dataset.transactions"
GROUP BY
  ROLLUP (country);

Not currently supported: GROUP BY ALL.

​
Window functions and QUALIFY

Window functions compute a value over a window of rows related to the current row, using OVER (PARTITION BY ... ORDER BY ... [frame]). ROWS frames with literal bounds are supported (e.g. ROWS BETWEEN 1 PRECEDING AND CURRENT ROW).

The QUALIFY clause filters on window function results, the way HAVING filters on aggregate results. A query must contain at least one window function to use QUALIFY:

SELECT
  user_id,
  amount,
  row_number() OVER (
    PARTITION BY
      user_id
    ORDER BY
      created_at DESC
  ) AS rn
FROM
  "my_bigquery.my_dataset.transactions" QUALIFY rn <= 3;

Not currently supported in window functions: the FILTER clause, frame EXCLUDE options, non-literal frame bounds, and RANGE frames with offset bounds (the default frame implied by ORDER BY works).

​
ORDER BY clause

Use ORDER BY with a list of sort keys or with ALL to sort by every selected column from left to right. Each <sort_key> has this form.

syntax
< expression > [ASC | DESC] [NULLS {FIRST | LAST}]

Sort keys can also be positions in the SELECT list, as in ORDER BY 2. The default sort direction is ASC. You can apply the same direction and null ordering to every selected column with ORDER BY ALL.

​
LIMIT and OFFSET clauses

LIMIT restricts the number of returned rows and OFFSET skips rows before returning. Use a literal integer for each count. You can use either clause on its own or put the two clauses in either order.

SELECT
  *
FROM
  "my_postgres.public.users"
ORDER BY
  user_id
LIMIT
  100
OFFSET
  200;

​
Set operations

Combine two queries with a set operator. You can chain set operations.

syntax
<select_statement> { UNION [ ALL ] | INTERSECT | EXCEPT } <select_statement>

UNION removes duplicate rows. UNION ALL keeps them.

An ORDER BY following a set operation may only reference output column names or positions. To apply a LIMIT (or sort by a computed expression), wrap the set operation in a subquery:

SELECT
  *
FROM
  (
    SELECT
      user_id
    FROM
      "my_postgres.public.users"
    UNION
    SELECT
      user_id
    FROM
      "my_postgres.public.archived_users"
  )
ORDER BY
  user_id
LIMIT
  50;

​
Subqueries

Subqueries are supported in the FROM clause, as scalar expressions, and in IN / EXISTS predicates, including correlated forms:

SELECT
  *
FROM
  "my_postgres.public.users" u
WHERE
  EXISTS (
    SELECT
      1
    FROM
      "my_bigquery.my_dataset.transactions" t
    WHERE
      t.user_id = u.user_id
      AND t.amount > 10000
  );

Some constructs are not currently supported inside subqueries, including GROUP BY within an EXISTS subquery and DISTINCT in correlated scalar subqueries. Use ARRAY(SELECT ...) to collect a single-column subquery into an array.