SQL Analytics Functions: Aggregates, Time Buckets, and Scalar Operations
How Cloudflare Analytics Engine, Basin SQL, and Basin Pipelines SQL functions work—aggregates, time grouping, strings, math, and common naming traps.
This page summarises Cloudflare documentation for SQL-style functions used to query analytics and pipeline data: Analytics Engine, Basin SQL, and Basin Pipelines scalar and aggregate references. The cluster also includes the separate Rules language functions for HTTP rule expressions; those are not SQL and are mentioned only where naming looks similar.
Which SQL function reference applies: Analytics Engine, Basin SQL, or Basin Pipelines
Section titled “Which SQL function reference applies: Analytics Engine, Basin SQL, or Basin Pipelines”Cloudflare publishes multiple SQL references because the underlying engines and call styles differ. Analytics Engine documents camelCase-style calls such as argMax, toDateTime, and bitAnd in the Analytics Engine SQL reference. Basin SQL documents familiar grouped aggregates (SUM, AVG, GROUP BY) and rich statistics (regr_slope, corr, string_agg) in Basin SQL aggregate functions and a broad scalar functions index. Basin Pipelines reuses many PostgreSQL-like names (coalesce, date_trunc, regexp_match) under Basin Pipelines scalar functions.
Before writing a query, open the reference that matches the product you query. The same English word often maps to different spellings or semantics (see the comparison table below).
| Concern | Analytics Engine | Basin SQL / Basin Pipelines |
|---|---|---|
| Aggregate “pick row at extreme” | argMax(arg, val), argMin(arg, val) |
first_value / last_value with ORDER BY in the aggregate |
| Bitwise on values | Scalar bitAnd(a, b) (bit functions) |
Group bit_and, bit_or, bit_xor (aggregates) |
| Natural log | log(expression) — natural log; ln alias (mathematical functions) |
log(base, numeric_expression) or log(numeric_expression) for base 10 (math functions) |
| String prefix test | startsWith(string, string) (string functions) |
starts_with(str, substr) (string functions) |
| Rules vs SQL strings | — | Rules: starts_with(source, substring) on fields, not literals (Rules language) |
Aggregate functions: sums, extremes, regression, and “which row had the max”
Section titled “Aggregate functions: sums, extremes, regression, and “which row had the max””Aggregates collapse many rows into one value (or one value per GROUP BY key). In Basin SQL, basic totals and spreads are documented with standard patterns:
Returns the sum of values in a column.
— Cloudflare, Basin SQL aggregate functions
SUM, AVG (alias mean), MIN, and MAX work on numeric and, for min/max, string columns. For distribution and relationship analysis, Basin SQL adds sample and population variance (var, var_pop), standard deviation (stddev, stddev_pop), covariance (covar_samp, covar_pop), Pearson corr, and the regr_* family (regr_slope, regr_intercept, regr_r2, and related helpers)—all shown with GROUP BY examples in the same reference.
Analytics Engine emphasises a different pattern: returning which dimension value belonged to the extreme, not only the extreme number:
argMax is an aggregation function that returns the arg value that corresponds to the maximum value of val.
If multiple arg values have the maximum value of val, any one will be returned.
— Cloudflare, Analytics Engine aggregate functions
The mirror argMin(arg, val) returns the arg at the minimum val. Docs also show argMax(blob1, _sample_interval) to pick a field from the most heavily sampled row—typical for sampled telemetry. Simple min(column_name) returns the minimum across rows. first_value and last_value in Analytics Engine return the first/last value of a column; examples pair them with ORDER BY on timestamps.
Basin SQL’s ordered picks are expressed inside the aggregate:
Returns the first value in a group according to the specified ordering.
— Cloudflare, Basin SQL aggregate functions
Use first_value(customer_id ORDER BY total_amount ASC) (and the corresponding last_value) when you need “customer with lowest spend per department,” not just the minimum amount.
Other Basin aggregates worth knowing: bool_and / bool_or for predicates across a group, string_agg for delimited lists, and bitwise group folds bit_and, bit_or, bit_xor.
Time and date functions: parsing, parts, and time buckets for charts
Section titled “Time and date functions: parsing, parts, and time buckets for charts”Time functions fall into three jobs: parse or convert timestamps, extract parts, and round down to buckets for GROUP BY.
Analytics Engine: toDateTime, components, and toStartOfInterval
Section titled “Analytics Engine: toDateTime, components, and toStartOfInterval”toDateTime converts numbers or strings into a datetime. Non-UTC values need an explicit zone:
toDateTime converts an expression to a datetime. This function does not support ISO 8601-style timezones; if your time is not in UTC then you must provide the timezone using the second optional argument.
— Cloudflare, Analytics Engine date and time functions
Examples accept Unix seconds in a numeric column, YYYY-MM-DD hh:mm:ss strings, or a zone such as 'America/New_York'. Extraction helpers include toYear, toMonth, toDayOfWeek (Monday = 1 through Sunday = 7), toHour, and toUnixTimestamp(now()).
For chart grain, toStartOfInterval rounds down to a fixed width:
toStartOfInterval rounds down a datetime to the nearest offset of a provided interval. This can be useful for grouping data into equal-sized time ranges.
— Cloudflare, Analytics Engine date and time functions
The docs count hourly events with toStartOfInterval(timestamp, INTERVAL '1' HOUR) and sum(_sample_interval). Named starters (toStartOfDay, toStartOfHour, toStartOfFiveMinutes, toStartOfWeek with Monday as week start, and others) avoid writing custom interval math. toYYYYMM returns a numeric year-month such as 202510.
Analytics Engine strings also support extract(SECOND from toDateTime(...)) for unit integers (string functions).
Basin Pipelines: date_bin, date_trunc, and epoch helpers
Section titled “Basin Pipelines: date_bin, date_trunc, and epoch helpers”Pipeline SQL documents date_bin for aligned windows with an optional origin:
Calculates time intervals and returns the start of the interval nearest to the specified timestamp. Use date_bin to downsample time series data by grouping rows into time-based “bins” or “windows” and applying an aggregate or selector function to each window.
— Cloudflare, Basin Pipelines time and date functions
date_trunc (alias datetrunc) truncates to units from year through second. date_part / extract expose the same parts, including dow, doy, epoch, and sub-second fields.
Parsing and precision differ by function family: to_timestamp, to_timestamp_millis, to_timestamp_micros, to_timestamp_nanos, and to_timestamp_seconds document RFC3339 strings, optional Chrono format strings, and integer epoch units at different resolutions (time and date functions). Read the bounds notes on to_timestamp before feeding very large integers.
now() in Basin Pipelines is fixed for the run:
Returns the UTC timestamp at pipeline start.
The now() return value is determined at query compilation time, and will be constant across the execution of the pipeline.
— Cloudflare, Basin Pipelines time and date functions
Basin SQL notes now() / current_timestamp precision is quantized to 10ms boundaries (scalar functions).
String functions: length, case, search, and split behaviour
Section titled “String functions: length, case, search, and split behaviour”String handling is the largest overlap between engines, with important encoding and indexing differences.
Analytics Engine strings
Section titled “Analytics Engine strings”length is UTF-8 aware and described as equivalent to ClickHouse lengthUTF8, not byte length (string functions). empty(string) tests for empty strings. ASCII-only lower / upper differ from Unicode-aware lowerUTF8 / upperUTF8 (aliases toLower / toUpper).
Search and slice use SQL-style 1-based offsets in position(needle IN haystack) (0 if not found) and substring(string, offset[, length]) counted in Unicode code points—offset should be at least 1. Prefix/suffix checks use startsWith and endsWith.
Basin SQL and Basin Pipelines strings
Section titled “Basin SQL and Basin Pipelines strings”Basin Pipelines documents PostgreSQL-like names: strpos / instr, split_part, substr, overlay, translate, levenshtein, regexp_match, regexp_replace with documented flags, and helpers such as uuid() (string, regex). Basin SQL scalar functions mirror many of the same capabilities in query examples (concat_ws, replace, initcap, and others).
For arrays from delimited text, Basin Pipelines array functions document string_to_array (alias string_to_list) with an optional null_str to map substrings to NULL.
Rules language strings (not SQL)
Section titled “Rules language strings (not SQL)”Rules language functions such as substring, starts_with, and trim_end operate on request fields; the source cannot be a literal string, and substring uses 0-based byte indexes with optional negative indices. Do not copy SQL substr arguments into rule expressions without re-checking indexing rules.
Conditional, math, bit, encoding, and hash helpers
Section titled “Conditional, math, bit, encoding, and hash helpers”Conditionals: Analytics Engine provides if(condition, true_expr, false_expr) (conditional functions). Basin Pipelines adds coalesce, nullif, nvl, and nvl2 (conditional); Basin SQL shows the same null-handling patterns in scalar functions.
Math: Basin Pipelines math functions cover trigonometry, hyperbolic functions, round/trunc with optional decimal places, random() per row in [0, 1), and nanvl for NaN replacement. Analytics Engine mathematical functions document pow, round, floor, and ceil with optional decimal precision.
Bits: Per-row bitwise work in Analytics Engine uses bitAnd, bitOr, bitXor, shifts, rotates, bitTest, bitCount, and bitHammingDistance (bit functions). Human-readable encodings use bin and hex (encoding functions).
Hashes: Basin Pipelines hashing documents digest(expression, algorithm) for md5, SHA-2 family, and Blake variants, plus standalone md5 / sha256 helpers. Basin SQL examples overlap in scalar functions.
Types: Analytics Engine type conversion includes toUInt8 and toUInt32, with undefined behaviour for negative inputs on unsigned converts—often paired with bitAnd(toUInt8(double1), 1) style extracts in bit function examples.
Binary strings: decode(expression, format) appears in Basin Pipelines binary string functions and Basin SQL (base64 in scalar examples).
Common mistakes when picking SQL functions
Section titled “Common mistakes when picking SQL functions”- Calling
log(x)expecting base 10 in Analytics Engine—it returns the natural logarithm (mathematical functions); use Basin’slog10or two-argumentlogwhere documented. - Using ASCII
loweron international text in Analytics Engine instead oflowerUTF8when Unicode case folding matters (string functions). - Assuming
from_unixtimealways means seconds; confirm Basin SQL versus Basin Pipelines definitions before grouping. - Using
argMaxwhen you only needmax—argMaxreturns a dimension, not the maximum metric alone (aggregate functions). - Feeding ISO timestamps with embedded offsets into
toDateTimewithout the second timezone argument when data is not UTC (date and time functions). - Mixing Rules
substringbyte indexes with SQL 1-based charactersubstring(Rules language vs Analytics Engine strings).
How to check this on your site
Section titled “How to check this on your site”-
Identify whether the query runs against Analytics Engine, Basin SQL, or a Basin Pipeline, then open the matching function index (Analytics Engine aggregates, Basin SQL aggregates, or Basin Pipelines time and date).
-
Run a minimal
SELECTthat uses one function from the reference (for exampleSUMwithGROUP BYortoStartOfIntervalwithsum(_sample_interval)) and confirm the result shape matches the documented example pattern. -
If results look wrong for time columns, re-check epoch units (
to_timestamp_secondsvsto_timestamp_millisvs Pipelinesfrom_unixtime) against Basin Pipelines time and date functions and Basin SQL scalar functions. -
For string or regex helpers, compare function names (
startsWithvsstarts_with) in Analytics Engine string functions versus Basin Pipelines string functions. -
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 disagrees with the linked Cloudflare references or does not match what you see in a query, email yimasynthetic@gmail.com with the page URL and the exact sentence or function call you are questioning.