Apache Iceberg SQL: Aggregations, GROUP BY, HAVING, and OFFSET
How Cloudflare Basin SQL queries Iceberg tables with aggregations, GROUP BY, HAVING, LIMIT OFFSET pagination, joins, and read-only limits.
This page summarizes Cloudflare documentation on Basin SQL (formerly R2 SQL): a serverless, distributed SQL engine for querying large Apache Iceberg tables in Basin Catalog without managing or scaling compute. If you need ranked summaries, filtered groups, or paged result sets on cataloged Iceberg data, the material below is the reference path.
Basin SQL: what it is and how you run queries
Section titled “Basin SQL: what it is and how you run queries”Basin SQL is Cloudflare’s read-only analytics query layer over Iceberg tables registered in Basin Catalog. You run queries through Wrangler or the HTTP API, as described on Query data.
Basin SQL, formerly R2 SQL, is a serverless, distributed SQL engine for querying large Apache Iceberg tables in Basin Catalog without managing or scaling compute.
— Cloudflare, Cloudflare Basin is now generally available
With Basin SQL you can:
- Summarize and rank data with standard and approximate aggregates, grouping sets, and window functions.
- Combine and inspect datasets with joins, subqueries, common table expressions, set operations, schema discovery, and
EXPLAIN. - Transform strings, timestamps, JSON, and complex values with more than 190 functions.
The supported grammar is documented in the Basin SQL SQL reference. Basin SQL supports joining multiple Iceberg tables in a single query with standard SQL join syntax, subqueries in multiple positions, and multi-table CTEs (JOIN clause, R2 SQL now supports JOINs, subqueries, and multi-table queries).
Aggregation functions: COUNT, SUM, AVG, and related aggregates
Section titled “Aggregation functions: COUNT, SUM, AVG, and related aggregates”Aggregation functions compute a single value from many rows. On Iceberg tables in Basin Catalog (and historically R2 Data Catalog), Cloudflare documents standard SQL aggregates including COUNT(*), SUM(), AVG(), MIN(), and MAX(), used together with GROUP BY and HAVING (R2 SQL now supports aggregations and schema discovery).
A typical pattern filters rows with WHERE, groups dimensions with GROUP BY, then restricts groups with HAVING:
SELECT department, COUNT(*), AVG(total_amount)FROM my_namespace.sales_dataWHERE region = 'North'GROUP BY departmentHAVING COUNT(*) > 50ORDER BY AVG(total_amount) DESCFor totals per group without a row filter on aggregates:
SELECT department, SUM(total_amount)FROM my_namespace.sales_dataGROUP BY departmentHAVING SUM(total_amount) > 50000Later releases expanded the grammar with 33 aggregate functions, window functions, SELECT DISTINCT, and set operations (R2 SQL now supports over 190 new functions, expressions, and complex types). For high-cardinality metrics, Basin SQL also exposes five approximate aggregation functions that trade minor precision for speed (R2 SQL now supports approximate aggregation functions); Limitations and best practices names approx_distinct, approx_median, and approx_percentile_cont as preferable to exact equivalents on large datasets.
avgIf and conditional aggregates (Workers Analytics Engine)
Section titled “avgIf and conditional aggregates (Workers Analytics Engine)”If you query Workers Analytics Engine rather than Basin Catalog Iceberg tables, conditional aggregates such as avgIf apply: the mean of one expression only where a second expression is true (Aggregate functions).
avgIf(item_cost, in_stock > 0)That pattern is separate from Basin SQL’s Iceberg analytics path but shares the same mental model: aggregate only the rows that match a predicate.
GROUP BY: how to group rows for aggregation
Section titled “GROUP BY: how to group rows for aggregation”GROUP BY defines the buckets over which aggregations run. When you use aggregate functions, each non-aggregated column in SELECT must appear in GROUP BY (standard SQL).
When using aggregate functions, GROUP BY specifies the groups over which the aggregation is run.
— Cloudflare, Statements — GROUP BY clause
Example from the same reference:
SELECT blob1 AS probe_name, avg(double1) AS average_tempFROM temperature_readingsGROUP BY probe_nameCloudflare notes that GROUP BY expressions can be column names or more complex expressions, and you may list several expressions separated by commas. The Basin SQL SQL reference shows the aggregation shape explicitly:
SELECT column_list, aggregation_function(column) AS aliasFROM namespace_name.table_nameGROUP BY column_listHAVING aggregation_function(column) comparison_operator valueQualify tables as namespace_name.table_name when querying catalog namespaces (for example my_namespace.sales_data in changelog examples).
HAVING: filter groups after aggregation (not the same as WHERE)
Section titled “HAVING: filter groups after aggregation (not the same as WHERE)”People often confuse WHERE and HAVING. WHERE filters rows before grouping. HAVING filters groups after aggregation completes.
The HAVING clause complements the WHERE clause by enabling you to filter groups based on aggregate values. While WHERE filters rows before aggregation, HAVING filters groups after aggregation is complete.
— Cloudflare, Workers Analytics Engine SQL now supports filtering using HAVING and LIKE
On Workers Analytics Engine, the reference adds:
HAVING is used to filter the results after grouping and aggregation. … Unlike WHERE, which filters rows before grouping, HAVING filters groups after aggregation.
— Cloudflare, Statements — HAVING clause
HAVING conditions may reference aggregate functions, grouped columns, comparison operators, and boolean combinations (AND / OR). Examples:
SELECT blob1 AS probe_name, avg(double1) AS average_tempFROM temperature_readingsGROUP BY probe_nameHAVING average_temp > 10SELECT blob1 AS probe_name, count() AS num_readingsFROM temperature_readingsGROUP BY probe_nameHAVING num_readings > 100SELECT blob1 AS city, avg(double1) AS avg_temp, count() AS readingsFROM weather_dataGROUP BY cityHAVING avg_temp > 20 AND readings >= 50The same HAVING semantics apply to Basin SQL aggregation queries on Iceberg tables (Filtering using HAVING and R2 SQL now supports aggregations and schema discovery).
| Clause | Applies to | Typical expressions |
|---|---|---|
WHERE |
Rows before GROUP BY |
Column predicates, no bare aggregates on grouped queries |
HAVING |
Groups after aggregates | AVG(...) > 10, COUNT(*) > 50, aliases from SELECT where supported |
GROUP BY |
Grouping keys | Dimensions, expressions |
LIMIT and OFFSET: pagination of query results
Section titled “LIMIT and OFFSET: pagination of query results”Basin SQL supports OFFSET to skip leading rows when retrieving results. Pair LIMIT (page size) with OFFSET (rows to skip).
Basin SQL is a serverless, distributed SQL engine for querying Apache Iceberg tables in Basin Catalog. It now supports OFFSET, which lets you skip a specified number of rows when retrieving query results.
— Cloudflare, Basin SQL supports OFFSET
Use LIMIT to set the page size and OFFSET to skip earlier rows. With a page size of 100, use OFFSET 0 for the first page, OFFSET 100 for the second, and increase the offset by 100 for each later page. Add ORDER BY on a unique column to keep the row order consistent.
— Cloudflare, Basin SQL supports OFFSET
Second page of 100 rows:
SELECT sale_id, total_amountFROM my_namespace.sales_dataORDER BY sale_idLIMIT 100 OFFSET 100Without a stable ORDER BY (ideally on a unique key), page boundaries can shift between requests. Use Limitations and best practices guidance to keep scans bounded: time-range filters in WHERE, explicit column lists, and LIMIT on large exploratory queries.
Set operations, window functions, and complex types
Section titled “Set operations, window functions, and complex types”Beyond single-table aggregates, Basin SQL supports:
| Capability | Purpose |
|---|---|
UNION, INTERSECT, EXCEPT, SELECT DISTINCT |
Combine or deduplicate result sets (changelog) |
| Window functions | Rank and analyze within partitions without collapsing rows (changelog) |
| Struct, array, map | Query nested Iceberg columns (Complex types) |
| Scalar functions | Per-value transforms in SELECT, WHERE, GROUP BY, HAVING, ORDER BY (Scalar functions) |
Scalar helpers such as arrow_cast(expression, datatype) and arrow_typeof(expression) expose Apache Arrow type names when you need typed casts or debugging (Scalar functions).
Basin Pipelines uses a different SQL surface (stream INSERT INTO … SELECT transformations, DataFusion-based scalars). It is not the same runtime as Basin SQL on Iceberg catalogs (SELECT statements, Scalar functions). Use Basin SQL when analyzing tables already in Basin Catalog; use Basin Pipelines when transforming streams into sinks.
Performance limits and common mistakes
Section titled “Performance limits and common mistakes”Cloudflare’s Limitations and best practices and Troubleshooting guide align on the same themes:
- Include time-range filters in
WHEREto limit data scanned (partition/timestamp filters are called out as the most important optimization in troubleshooting). - Prefer named columns over
SELECT *. - Use
LIMITto cap result size during exploration. - Prefer approximate aggregates on very large or high-cardinality data when exact precision is unnecessary.
- Enable compaction in Basin Catalog to reduce files per query.
- Run
EXPLAINto verify predicate pushdown and file pruning. - On multi-way JOINs, filter early; avoid joining two large fact tables without dimension tables in between.
- Be cautious with
COUNT(DISTINCT)across multi-way joins; considerapprox_distinct()or smaller staged queries.
Common mistakes:
- Using
HAVINGto filter raw rows that belong inWHERE(hurts performance and can be invalid depending on expressions). - Paginating with
OFFSETwithoutORDER BYon a unique column (unstable pages). - Issuing
ALTER TABLE,UPDATE, orCREATE TABLEagainst Basin SQL (read-only; manage schema via pipelines and catalog). - Heavy
SELECT *over wide Iceberg tables without partition filters.
How to check this on your site
Section titled “How to check this on your site”-
Confirm your Iceberg tables are visible in Basin Catalog and note the
namespace.tablenames you will query (Query data). -
Run a small aggregation with
GROUP BYandHAVINGon a filtered time range, matching the patterns in R2 SQL now supports aggregations and schema discovery. -
Run
EXPLAINon the same query and check that partition or timestamp predicates appear in the plan (Troubleshooting guide — Query performance issues). -
Test pagination with
ORDER BY,LIMIT, andOFFSETusing the example from Basin SQL supports OFFSET. -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match your environment or the linked Cloudflare docs, email yimasynthetic@gmail.com with the page URL and the exact sentence you think is wrong or unclear.