Implement the SQL-standard ordered-set aggregate syntax
`f(args) WITHIN GROUP (ORDER BY x)` for mode(), percentile_cont() and
percentile_disc() as first-class core aggregates, documented under
docs/sql-reference/functions/aggregate.mdx.
WITHIN is a context-sensitive keyword (only after `)` + GROUP), so it
remains usable as an identifier. The planner rewrites the ordered-set
form into uniform aggregate args and rejects unsupported variants
(DESC/NULLS, multi-column ORDER BY, DISTINCT) with clear errors rather
than returning wrong results.
The percentile fraction is a direct argument: it must be constant with
respect to the aggregated rows. A reference to the query's own input
columns (directly or via a subquery) is rejected, while an outer
(correlated) column is allowed, matching PostgreSQL. A constant fraction
is folded and range-checked at compile time, so an out-of-range fraction
errors regardless of row count (empty / all-NULL / all-filtered input).
Text ordered sets are collation-aware: mode() and percentile_disc() sort
using the value's collation (explicit COLLATE, column-declared collation,
or the BINARY default), recorded in the aggregate payload at step time
and applied when sorting at finalize.
Validated against PostgreSQL 18 across the accept-path plus corner cases
(subqueries, CTEs, FILTER, HAVING, correlated references including an
outer-column fraction, constant-expression fractions, expression/CASE
order keys, and attached databases). The BINARY default matches PG
`COLLATE "C"`; NOCASE / column collations are honored consistently with
ORDER BY. Extension-registered Custom collations fall back to BINARY at
finalize, consistent with the engine's other connection-less comparison
paths.
Tests wrap percentile_cont (REAL) results in CAST(... AS TEXT) so the
whole-number float comparison is stable across the rust, cli and js test
backends (the js backend renders 3.0 as "3").
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Comprehensive SQL reference at docs/sql-reference/ covering all
supported statements, functions, expressions, PRAGMAs, and
extensions. Includes mdBook-based local preview (./preview.sh).
Turso-specific features (CDC, materialized views, custom types,
MVCC, vector search, FTS, encryption) are integrated inline with
callouts. Experimental features link to a dedicated page with
enablement instructions for the CLI and all SDKs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>