From 594bc5ce28220f00acb18443ba2ba1343ee3105a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Manciot?= Date: Tue, 20 Oct 2026 20:53:21 +0200 Subject: [PATCH 1/3] docs(core): failed shards, Elasticsearch 6 paging order and the window default since 0.24.0 Documents three 0.24.0 behaviours the reference did not carry. A search on which some shards fail answers an error, not the other shards' rows (search: the message and status; scroll: every paging path; the SQL ORDER BY note links both). search_after needs no ORDER BY: it pages on _id, which since 0.24.0 tolerates an Elasticsearch 6 index created without any mapping. ScrollConfig gains failOnWindowError, whose default now fails a statement whose window values cannot be computed. Also carries what the public site states and this reference lacked: the JOIN UNNEST key notes and the 0.24.0 stamp of the GROUP BY key conditions, POINT's argument rules, the Transact-SQL CONVERT order and three cast notes, the watcher refusal of table-qualified columns over several indices, and the GROUP BY refusal of a key formatting a bare date column on Elasticsearch 6. The DDL bullet on a narrowing cast now agrees with the / operator: a division is always a DOUBLE. Co-Authored-By: Claude Opus 5.5 --- documentation/client/scroll.md | 37 ++++++++++++++++++- documentation/client/search.md | 23 ++++++++++++ documentation/sql/ddl_statements.md | 18 ++++++--- documentation/sql/dql_statements.md | 26 ++++++++++--- .../sql/functions_type_conversion.md | 3 ++ documentation/sql/type_conversion.md | 10 +++-- 6 files changed, 102 insertions(+), 15 deletions(-) diff --git a/documentation/client/scroll.md b/documentation/client/scroll.md index 14dc2fab0..466244515 100644 --- a/documentation/client/scroll.md +++ b/documentation/client/scroll.md @@ -235,7 +235,7 @@ count (an explicit ceiling below it is still a whole-shard split on the Elastics **Limitations:** - ❌ Not supported with aggregations -- ❌ Requires sort fields +- ⚠️ Needs a total order: the client pages on `_id` (see below) - ⚠️ No consistent snapshot (data can change between pages) ```scala @@ -253,6 +253,16 @@ val query = SQLQuery( client.scroll(query).runWith(Sink.seq) ``` +**The `_id` order.** A statement needs no `ORDER BY` to be paged with `search_after`: without one, +the client pages in `_id` order (ascending); with one, it appends `_id` as the tie-breaker unless +the sort already names it. Since **0.24.0** that `_id` sort carries `unmapped_type: keyword`. On +Elasticsearch 6 an index created without any mapping has no type, hence no `_id` to sort on, so +every shard of such an index failed the page, and a statement without `LIMIT` over a pattern that +includes one failed even when that index was empty; it is now read like the others. `_id` is +mapped in every other index, where the key changes nothing. The Elasticsearch 7 client pages the +same way below 7.12 and carries the same key; whether 7.0 – 7.11 failed such an index is not +measured. + --- ### Classic Scroll @@ -317,6 +327,10 @@ case class ScrollConfig( // Retry configuration retryConfig: RetryConfig = RetryConfig(), + // A statement without LIMIT whose window values cannot be computed: + // None or Some(true) fails the stream; Some(false) answers the rows without them + failOnWindowError: Option[Boolean] = None, + // Ceiling on concurrent PIT slices for a no-ORDER-BY extraction (ES 7.15+, 0.21.0+). // None = inherit the client's `elastic.scroll.max-slices`; Some(n) explicit, n <= 1 sequential maxSlices: Option[Int] = None, @@ -341,9 +355,18 @@ explicit fields but still inherits the configured ceiling through `maxSlices = N | `preferSearchAfter` | `Boolean` | `true` | Prefer search_after when available | | `logEvery` | `Int` | `10` | Log progress every N batches | | `metrics` | `ScrollMetrics` | `ScrollMetrics()` | Initial metrics state | +| `failOnWindowError` | `Option[Boolean]` | `None` | When the window values of a statement without `LIMIT` cannot be computed: `None` or `Some(true)` fails the stream, `Some(false)` answers the rows without them (see below) | | `maxSlices` | `Option[Int]` | `None` | Ceiling on concurrent PIT slices; `None` inherits `elastic.scroll.max-slices` (default 8), `Some(1)` pages sequentially | | `slices` | `Int` | `1` | Internal — the resolved slice count (read it on `ScrollMetrics.slices`) | +**Window functions: `failOnWindowError`.** A statement without `LIMIT` that carries a window +function first computes its window values with an aggregation, then pages its rows and adds the +values to each one. When those values cannot be computed — for instance because some shards of the +window aggregation fail — the stream fails with `Window function computation failed: …`. That is +the default since **0.24.0** (`None`), and what `Some(true)` asks for. `Some(false)` answers the rows +**without** their window values, a wrong answer for every projected window column, so it is an +explicit opt-in only. Before 0.24.0 the default was that fallback. + --- ### ScrollMetrics @@ -707,6 +730,18 @@ is the right place to decide what a partial read means for your application. The failure is deliberately **not** retried: a scroll cursor that has already advanced cannot be re-polled without skipping rows. +### A page on which some shards fail fails the stream + +Elasticsearch answers a page on which **some** shards fail with HTTP 200 and the hits of the +shards that succeeded. Every paging path reads the page's `_shards` section, and a page with a +failed shard fails the stream with the shards' reasons — `Initial scroll failed: …`, +`Scroll continuation failed: …` (the scroll context is released and the page is not retried), +`Search after failed: …` or +`PIT search_after failed: …` — instead of handing over the other shards' rows as if they were the +whole page. The Elasticsearch 6 Jest client does so since **0.24.0**; before it, its three paging +doors judged a page by its HTTP status only. A one-shot search answers the same condition with an +error too — see [Search: a search whose shards fail](search.md#a-search-whose-shards-fail). + ```scala // Automatic error handling is built-in client.scroll(query).runWith(Sink.seq).recover { diff --git a/documentation/client/search.md b/documentation/client/search.md index ee9f93d56..7ec227feb 100644 --- a/documentation/client/search.md +++ b/documentation/client/search.md @@ -1700,6 +1700,29 @@ client.singleSearchAs[Product](query, Map.empty, Map.empty) match { --- +### A search whose shards fail + +Elasticsearch answers a search on which **some** shards fail with HTTP 200, `_shards.failed > 0`, +and the hits / buckets of the shards that succeeded only. Since **0.24.0** every one-shot search +reads that section and answers an `ElasticFailure` instead of those partial rows: + +- the message is `n of m shards failed`, then the first failure's type and reason, and its cause + when Elasticsearch gives one: `1 of 3 shards failed: null_pointer_exception: …`; +- `statusCode` is `400` when **every** failure is one Elasticsearch attributes to the request + (`script_exception`, `query_shard_exception`, `illegal_argument_exception`, `parsing_exception`, + `search_parse_exception`, `x_content_parse_exception`), and `None` otherwise; +- a multi-search is read response by response: the first one whose shards failed answers the + error, prefixed with its 1-based position (`Query 2: 1 of 3 shards failed: …`). + +`skipped` shards are not failures. Before 0.24.0 the one-shot searches did not read `_shards`, so +such a search answered the other shards' rows as the whole result, with no error. The paging paths +fail the same way page by page — see +[Scroll: a page on which some shards fail](scroll.md#a-page-on-which-some-shards-fail-fails-the-stream). +For the SQL statement that most often meets it, see +[`ORDER BY` over a function of a column some documents do not carry](../sql/dql_statements.md#where). + +--- + ### Multi-Search Partial Failures ```scala diff --git a/documentation/sql/ddl_statements.md b/documentation/sql/ddl_statements.md index f113c08ef..9b82cfb60 100644 --- a/documentation/sql/ddl_statements.md +++ b/documentation/sql/ddl_statements.md @@ -539,11 +539,13 @@ ran without error before: - **A cast of a string column now COMPUTES.** `SCRIPT AS (CAST(amount_str AS BIGINT) + fee)` sums the two. Before 0.24.0 it concatenated the two renderings — `'125'` and `7` stored `1257` rather than `132`, with no error. -- **A cast of a NUMERIC column to a different numeric type now decides the result type.** - `CAST(price AS INTEGER) / 2` over `price = 5.0` is `2`, because `CAST(price AS INTEGER)` really is - an integer; before 0.24.0 the column's own type won and it was `2.5`. The widening direction moves - the same way: `CAST(qty AS DOUBLE) / 2` over an `INTEGER` column is now `2.5` where it was `2`. - `WHERE` clauses over such an expression therefore match a different set of rows. +- **A cast of a NUMERIC column to a different numeric type now decides the OPERAND's type** in + the arithmetic around it: `CAST(price AS INTEGER)` really is an integer. It does not decide a + division: `/` always yields a `DOUBLE` whatever its operands are, so `CAST(price AS INTEGER) / 2` + over `price = 5.0` is `2.5` — the cast narrows the operand, it does not make the division + integral — and `CAST(qty AS DOUBLE) / 2` over an `INTEGER` column is `2.5` where it was `2`. + Write `(a / b)::INTEGER` for a truncated quotient. `WHERE` clauses over such an expression + therefore match a different set of rows. - **A numeric column cast to a string now CONCATENATES.** `CAST(qty AS KEYWORD) + 2` yields `'42'`-style text; before 0.24.0 the string was silently parsed back to a number and the expression computed. Under `-`, `*` and `/` the same shape is now a runtime failure rather than a @@ -1058,6 +1060,12 @@ FROM logs-*, metrics-* WHERE level = 'ERROR' WITHIN 5 MINUTES > Pre-join the sources with a [`MATERIALIZED VIEW`](materialized_views.md) and point the watcher > at the view instead. > +> **Table-qualified columns over a multi-index `FROM`** are rejected at parse time too: one search +> applies one query to *every* index it names, so it can neither join them +> (`FROM orders o, customers c WHERE o.id = c.order_id`) nor scope a predicate to one of them +> (`FROM orders, refunds WHERE orders.status = 'FAILED'`). `FROM logs-2025, logs-2024 WHERE +> level = 'ERROR'` is fine: no qualifier. + A table alias may be used and is resolved in the `WHERE`, so `FROM orders o WHERE o.status = 'FAILED'` searches index `orders` for documents whose **`status`** field is `FAILED`. diff --git a/documentation/sql/dql_statements.md b/documentation/sql/dql_statements.md index e9d474f39..ca531443d 100644 --- a/documentation/sql/dql_statements.md +++ b/documentation/sql/dql_statements.md @@ -461,9 +461,13 @@ The `WHERE` clause supports: > those 5 rows as the whole result, with no error. > > A statement without `LIMIT` is read page by page and fails the same way -> (`PIT search_after failed: …`). To sort such a column, sort by the bare column, or keep the field -> present on every document. The same applies to `ORDER BY` over a `CASE … END` with no `ELSE`, -> which is NULL-valued for the rows no branch matches. +> (`PIT search_after failed: …`). This is not specific to sorting: since **0.24.0**, a search on +> which some shards fail answers an error — `n of m shards failed`, then the first failure's type +> and reason — never the rows of the shards that succeeded (see +> [Search: a search whose shards fail](../client/search.md#a-search-whose-shards-fail)). To sort +> such a column, sort by the bare column, or keep the field present on every document. The same +> applies to `ORDER BY` over a `CASE … END` with no `ELSE`, which is NULL-valued for the rows no +> branch matches. > > Since **0.24.0**, a sort by the bare column over an index pattern or list also answers the > documents of an index that does not map that column, sorted as `NULL`, when the other indices map @@ -1542,8 +1546,8 @@ ORDER BY COUNT(*) DESC; ``` - `GROUP BY` supports nested fields (`profile.city`). -- A key over a date column, or over a function of any column, groups by the key's own value from - a single index, an index pattern or a list of indices: +- Since **0.24.0**, a key over a date column, or over a function of any column, groups by the key's + own value from a single index, an index pattern or a list of indices: - `DATE_TRUNC(created_at, MONTH)` is one Elasticsearch `date_histogram` level with that calendar interval; - a bare date column (`GROUP BY created_at`) is a `terms` level on the field: one group per @@ -1653,12 +1657,16 @@ generated comparison is text against a number and Elasticsearch fails the whole ### Conditions on the GROUP BY key A `HAVING` condition over the grouping key filters GROUPS, and it is applied by the `terms` filter — -so it is correct for a multi-valued field, where one document belongs to several groups. +so it is correct for a multi-valued field, where one document belongs to several groups. The rules +below hold since **0.24.0**; before it, several of the conditions now refused returned a +plausible-looking but wrong set of groups, without an error. ```sql SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city = 'Paris'; SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city LIKE 'P%'; SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city <> 'Lyon'; +SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city IN ('Paris', 'Lyon'); +SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city NOT IN ('Pau', 'Pise'); ``` - Supported: a direct comparison of the key — `=`, `<>`, `IN`, `LIKE` / `RLIKE` — whether the key @@ -1979,6 +1987,11 @@ FROM dql_sales ORDER BY product, ts; ``` +Since **0.24.0**, a statement without `LIMIT` whose window values cannot be computed — for instance +because shards of the window aggregation fail — answers an error, +`Window function computation failed: …`. Before 0.24.0 it answered its rows without their window +values (see [`failOnWindowError`](../client/scroll.md#scrollconfig)). + #### ROW_NUMBER / RANK / DENSE_RANK (ranking windows) `ORDER BY` is REQUIRED inside `OVER` for ranking functions (ANSI). `PARTITION BY` @@ -2444,6 +2457,7 @@ Notes: paged in `_id` order, and with one `_id` is the tie-breaker. Since `0.24.0`, on Elasticsearch 6, a statement without `LIMIT` over a pattern that includes an index created without any mapping is read in full, even when that index is empty: the `_id` order no longer fails that index's shards + (see [The `_id` order](../client/scroll.md#search_after)) - Without `ORDER BY`, result ordering is not guaranteed ### When some shards fail diff --git a/documentation/sql/functions_type_conversion.md b/documentation/sql/functions_type_conversion.md index 5f24f3019..c0aba99d8 100644 --- a/documentation/sql/functions_type_conversion.md +++ b/documentation/sql/functions_type_conversion.md @@ -47,6 +47,9 @@ Three limitations, stated plainly rather than hidden: `CONVERT(expr USING )` is accepted as a synonym for `CONVERT(expr, VARCHAR)`: Elasticsearch stores UTF-8 throughout, so the charset is parsed and dropped. +`CONVERT` also accepts the Transact-SQL argument order, the type first: `CONVERT(BIGINT, expr)` is +`CONVERT(expr, BIGINT)`. + **Output:** - Value converted to target `TYPE` diff --git a/documentation/sql/type_conversion.md b/documentation/sql/type_conversion.md index 37e4af7e9..d86387c41 100644 --- a/documentation/sql/type_conversion.md +++ b/documentation/sql/type_conversion.md @@ -29,7 +29,7 @@ SELECT CAST('2025-09-11' AS DATE) AS d FROM logs; ## Function: TRY_CAST (Alias: SAFE_CAST) **Description:** -Attempts to convert a value to a specified SQL type. Returns `NULL` if the conversion fails instead of raising an error. +Attempts to convert a value to a specified SQL type. Returns `NULL` if the conversion fails instead of raising an error. `SAFE_CAST` is accepted as an alias and normalises to `TRY_CAST`. **Inputs:** - `value` (ANY type) @@ -71,7 +71,7 @@ SELECT '2025-09-11'::DATE AS d, '125'::BIGINT AS b FROM logs; - `CAST` (`CONVERT`) will raise errors on invalid conversions. - `TRY_CAST` (`SAFE_CAST`) returns `NULL` instead of failing. - `::` is syntactic sugar, easier to read in queries. -- Type inference relies on `baseType`, and explicit `CAST`/`TRY_CAST`/`::` updates the type context for following functions. +- Type inference relies on `baseType`, and explicit `CAST`/`TRY_CAST`/`::` updates the type context for following functions, so `'125'::BIGINT + 1` is arithmetic rather than string concatenation. - *Since `0.25.0`.* A `BOOLEAN` cannot be cast to a `DATE`, a `TIME` or a `TIMESTAMP` — in a query, a computed column and a pipeline alike, with `CAST`, `TRY_CAST` or `::` — as DuckDB refuses it: `CAST(b AS DATE)` used to answer the boolean itself in a date column. @@ -90,6 +90,8 @@ SELECT '2025-09-11'::DATE AS d, '125'::BIGINT AS b FROM logs; `GREATEST(x, '1e400')` is refused (DuckDB answers `1.5` and `inf`). As a stored text compared with a `DOUBLE` column it is `+Infinity` or `-Infinity`, DuckDB's value: `k = x` is false and `k <> x` true. A stored `'NaN'` or `'Infinity'` fails the query. +- Casting is evaluated inside the generated Painless script, so a cast on a field participates in script-based filtering and sorting like any other expression. +- Without a `FROM` clause, a `SELECT` of constant expressions is accepted, and a constant cast works there in every spelling (see [FROM-less SELECT](dql_statements.md#from-less-select-connection-handshake)). --- @@ -104,7 +106,9 @@ SELECT MAX(salary)::BIGINT AS m FROM emp GROUP BY dept; SELECT CAST(MAX(salary) AS BIGINT) AS m FROM emp GROUP BY dept; ``` -All four spellings behave the same way — `::`, `CAST`, `TRY_CAST` and `CONVERT`. +All four spellings behave the same way — `::`, `CAST`, `TRY_CAST` and `CONVERT`. The same applies +in `HAVING`: `HAVING COUNT(*)::INT > 3` is rejected, and unnecessary — compare against a numeric +literal directly. Cast the aggregate's **input** instead. This is equivalent for `MIN` and `MAX`, whose result type follows their argument: From d858c759f9a453c388579cce853faef3389d2df0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Manciot?= Date: Tue, 20 Oct 2026 21:07:34 +0200 Subject: [PATCH 2/3] docs(core): correct statements the code no longer supports Known limitations no longer says INSERT, UPDATE, CREATE, DROP and ALTER names cannot be quoted: every statement takes them since the DQL, DML and DDL name rules were unified. The function references stop documenting what the parser rejects. LN, SGN, CURRENT_DATETIME and VERSION() are not functions of this engine, and PI is a constant written without parentheses. An alias that is a reserved word (distance, now, today, current_time, min, as, at, pi) does not parse and is renamed. POINT has no standalone form and is shown inside ST_DISTANCE; a FROM-less SELECT takes no WHERE; a JOIN on a distance, which an ON clause refuses, becomes a filtered count; and GREATEST / LEAST, the trigonometry and the Euclidean-distance examples no longer pass an arithmetic expression as a function argument. The DQL function tables gain the aliases the parser accepts (CEILING, POWER, LCASE, UCASE, LEN, STRPOS, CURDATE, CURTIME) and ISNULL / ISNOTNULL, and the precedence examples print a division as the DOUBLE it is. Every rewritten statement was parsed against the parser of this tree. Co-Authored-By: Claude Opus 5.5 --- documentation/sql/dql_statements.md | 29 +++-- documentation/sql/functions_conditional.md | 7 +- documentation/sql/functions_date_time.md | 21 ++- documentation/sql/functions_geo.md | 143 ++++++++++----------- documentation/sql/functions_math.md | 83 ++++++------ documentation/sql/functions_system.md | 5 +- documentation/sql/known_limitations.md | 5 +- documentation/sql/operator_precedence.md | 10 +- 8 files changed, 160 insertions(+), 143 deletions(-) diff --git a/documentation/sql/dql_statements.md b/documentation/sql/dql_statements.md index ca531443d..f4e12c866 100644 --- a/documentation/sql/dql_statements.md +++ b/documentation/sql/dql_statements.md @@ -2078,11 +2078,11 @@ All functions operate on Elasticsearch documents and are evaluated by the SQL en | Function | Description | |---------------|----------------------| | `ABS(x)` | Absolute value | -| `CEIL(x)` | Round up | +| `CEIL(x)` / `CEILING(x)` | Round up | | `FLOOR(x)` | Round down | | `ROUND(x, n)` | Round to n decimals | | `SQRT(x)` | Square root | -| `POW(x, y)` | Power | +| `POW(x, y)` / `POWER(x, y)` | Power | | `EXP(x)` | Exponential | | `LOG(x)` | Natural logarithm | | `LOG10(x)` | Base-10 logarithm | @@ -2109,7 +2109,7 @@ number: `ROUND(423789293, -5)` is `423800000`. See | `ACOS(x)` | Arc-cosine | | `ATAN(x)` | Arc-tangent | | `ATAN2(y, x)` | Arc-tangent of y/x with quadrant | -| `PI()` | π constant | +| `PI` | π constant (no parentheses) | | `RADIANS(x)` | Degrees → radians | | `DEGREES(x)` | Radians → degrees | @@ -2137,17 +2137,17 @@ FROM dql_users; |------------------------------|-------------------------------| | `CONCAT(a, b, ...)` | Concatenate strings | | `SUBSTRING(str, start, len)` | Extract substring | -| `LOWER(str)` | Lowercase | -| `UPPER(str)` | Uppercase | +| `LOWER(str)` / `LCASE(str)` | Lowercase | +| `UPPER(str)` / `UCASE(str)` | Uppercase | | `TRIM(str)` | Trim both sides | | `LTRIM(str)` | Trim left | | `RTRIM(str)` | Trim right | -| `LENGTH(str)` | String length | +| `LENGTH(str)` / `LEN(str)` | String length | | `REPLACE(str, from, to)` | Replace substring | | `LEFT(str, n)` | Left n chars | | `RIGHT(str, n)` | Right n chars | | `REVERSE(str)` | Reverse string | -| `POSITION(substr IN str)` | 1-based position of substring | +| `POSITION(substr IN str)` / `STRPOS(str, substr)` | 1-based position of substring | ##### **Pattern matching:** @@ -2178,11 +2178,11 @@ ORDER BY id ASC; | Function | Description | |-------------------------------------------|-----------------------------| -| `CURRENT_DATE` | Current date (UTC) | +| `CURRENT_DATE` / `CURDATE()` | Current date (UTC) | | `TODAY()` | Alias for CURRENT_DATE | -| `CURRENT_TIMESTAMP` \| `CURRENT_DATETIME` | Current timestamp (UTC) | +| `CURRENT_TIMESTAMP` | Current timestamp (UTC) | | `NOW()` | Alias for CURRENT_TIMESTAMP | -| `CURRENT_TIME` | Current time (UTC) | +| `CURRENT_TIME` / `CURTIME()` | Current time (UTC) | ##### **Extraction:** @@ -2347,6 +2347,15 @@ Returns NULL if `a = b`, otherwise `a`. `NULLIF(status, 0)` over a `KEYWORD` reads `status` as a `BIGINT`, and a `status` that spells no number fails the query. A computed column keeps refusing a text against a number. +##### ISNULL / ISNOTNULL + +```sql +ISNULL(expr) +ISNOTNULL(expr) +``` + +`ISNULL` is TRUE when `expr` is NULL, `ISNOTNULL` when it is not. + ##### GREATEST / LEAST ```sql diff --git a/documentation/sql/functions_conditional.md b/documentation/sql/functions_conditional.md index 474f9e2a3..6162eedc3 100644 --- a/documentation/sql/functions_conditional.md +++ b/documentation/sql/functions_conditional.md @@ -693,9 +693,12 @@ SELECT GREATEST(price_us, price_eu, price_uk) AS max_price FROM products ``` -**2. Floor on a computed value:** +**2. Floor on a computed value** — an arithmetic expression is not accepted as a function +argument, so compute it as a column first (see +[Known Limitations](known_limitations.md#arithmetic-is-not-accepted-inside-a-function-a-cast-or-a-case-branch)): ```sql -SELECT GREATEST(0, base_price - rebate) AS net +-- net_raw DOUBLE SCRIPT AS (base_price - rebate) in the table definition +SELECT GREATEST(0, net_raw) AS net FROM orders -- Never lets the net go below zero ``` diff --git a/documentation/sql/functions_date_time.md b/documentation/sql/functions_date_time.md index e4dd8cea2..b769676fb 100644 --- a/documentation/sql/functions_date_time.md +++ b/documentation/sql/functions_date_time.md @@ -12,7 +12,7 @@ This page documents TEMPORAL functions. ### Current Date/Time Functions -#### CURRENT_TIMESTAMP / NOW / CURRENT_DATETIME +#### CURRENT_TIMESTAMP / NOW Returns current datetime (ZonedDateTime) in UTC. @@ -20,9 +20,10 @@ Returns current datetime (ZonedDateTime) in UTC. ```sql CURRENT_TIMESTAMP NOW() -CURRENT_DATETIME ``` +`CURRENT_DATETIME` is a reserved word, not a function: `SELECT CURRENT_DATETIME` does not parse. + **Inputs:** - None @@ -31,14 +32,12 @@ CURRENT_DATETIME **Examples:** ```sql -SELECT CURRENT_TIMESTAMP AS now; +SELECT CURRENT_TIMESTAMP AS ts_now; -- Result: 2025-09-26T12:34:56Z -SELECT NOW() AS current_time; +SELECT NOW() AS t_now; -- Result: 2025-09-26T12:34:56Z -SELECT CURRENT_DATETIME AS dt; --- Result: 2025-09-26T12:34:56Z ``` --- @@ -62,13 +61,13 @@ TODAY() **Examples:** ```sql -SELECT CURRENT_DATE AS today; +SELECT CURRENT_DATE AS d_today; -- Result: 2025-09-26 -SELECT CURDATE() AS today; +SELECT CURDATE() AS d_today; -- Result: 2025-09-26 -SELECT TODAY() AS today; +SELECT TODAY() AS d_today; -- Result: 2025-09-26 ``` @@ -95,7 +94,7 @@ CURTIME() SELECT CURRENT_TIME AS t; -- Result: 12:34:56 -SELECT CURTIME() AS current_time; +SELECT CURTIME() AS t_now; -- Result: 12:34:56 ``` @@ -860,7 +859,7 @@ SELECT EXTRACT(HOUR FROM '2025-01-10T12:34:56Z'::TIMESTAMP) AS h; -- Result: 12 -- Extract minute -SELECT EXTRACT(MINUTE FROM '2025-01-10T12:34:56Z'::TIMESTAMP) AS min; +SELECT EXTRACT(MINUTE FROM '2025-01-10T12:34:56Z'::TIMESTAMP) AS minute_value; -- Result: 34 -- Extract second diff --git a/documentation/sql/functions_geo.md b/documentation/sql/functions_geo.md index 5fbfcbb29..1122b97fd 100644 --- a/documentation/sql/functions_geo.md +++ b/documentation/sql/functions_geo.md @@ -67,10 +67,10 @@ If both arguments are fixed points, the distance is **precomputed at query compi ```sql SELECT name, - ST_DISTANCE(POINT(48.8566, 2.3522), location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), location) AS dist FROM stores WHERE ST_DISTANCE(POINT(48.8566, 2.3522), location) < 5 km -ORDER BY distance ASC +ORDER BY dist ASC ``` **2. Distance range with BETWEEN (kilometers):** @@ -78,10 +78,10 @@ ORDER BY distance ASC SELECT name, address, - ST_DISTANCE(POINT(48.8566, 2.3522), location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), location) AS dist FROM stores WHERE ST_DISTANCE(POINT(48.8566, 2.3522), location) BETWEEN 4 km AND 10 km -ORDER BY distance ASC +ORDER BY dist ASC ``` **3. Multiple distance comparisons with different units:** @@ -102,11 +102,11 @@ SELECT name, cuisine, rating, - ST_DISTANCE(POINT(40.7128, -74.0060), location) AS distance + ST_DISTANCE(POINT(40.7128, -74.0060), location) AS dist FROM restaurants WHERE ST_DISTANCE(POINT(40.7128, -74.0060), location) <= 2 mi AND rating >= 4.0 -ORDER BY rating DESC, distance ASC +ORDER BY rating DESC, dist ASC LIMIT 20 ``` @@ -114,30 +114,30 @@ LIMIT 20 ```sql SELECT building_name, - ST_DISTANCE(POINT(48.8566, 2.3522), entrance_location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), entrance_location) AS dist FROM buildings WHERE ST_DISTANCE(POINT(48.8566, 2.3522), entrance_location) < 500 m -ORDER BY distance ASC +ORDER BY dist ASC ``` **6. Distance in feet:** ```sql SELECT landmark_name, - ST_DISTANCE(POINT(40.7128, -74.0060), location) AS distance + ST_DISTANCE(POINT(40.7128, -74.0060), location) AS dist FROM landmarks WHERE ST_DISTANCE(POINT(40.7128, -74.0060), location) <= 1000 ft -ORDER BY distance ASC +ORDER BY dist ASC ``` **7. Distance in nautical miles:** ```sql SELECT ship_name, - DISTANCE(port_location, ship_location) AS distance + DISTANCE(port_location, ship_location) AS dist FROM vessels WHERE DISTANCE(port_location, ship_location) < 50 nmi -ORDER BY distance ASC +ORDER BY dist ASC ``` **8. Distance between two fields:** @@ -159,7 +159,8 @@ ORDER BY distance_km DESC SELECT ST_DISTANCE( POINT(48.8566, 2.3522), -- Paris POINT(40.7128, -74.0060) -- New York -) AS distance +) AS dist +FROM stores WHERE ST_DISTANCE(POINT(48.8566, 2.3522), POINT(40.7128, -74.0060)) > 5000 km -- Distance is precomputed at query compilation time ``` @@ -169,12 +170,12 @@ WHERE ST_DISTANCE(POINT(48.8566, 2.3522), POINT(40.7128, -74.0060)) > 5000 km SELECT name, category, - ST_DISTANCE(POINT(51.5074, -0.1278), location) AS distance + ST_DISTANCE(POINT(51.5074, -0.1278), location) AS dist FROM points_of_interest WHERE ST_DISTANCE(POINT(51.5074, -0.1278), location) >= 1 km AND ST_DISTANCE(POINT(51.5074, -0.1278), location) <= 10 km AND category IN ('restaurant', 'cafe', 'bar') -ORDER BY distance ASC +ORDER BY dist ASC ``` **11. Using DISTANCE alias:** @@ -205,7 +206,7 @@ ORDER BY city_center_dist ASC SELECT order_id, customer_address, - ST_DISTANCE(warehouse_location, delivery_location) AS distance, + ST_DISTANCE(warehouse_location, delivery_location) AS dist, CASE WHEN ST_DISTANCE(warehouse_location, delivery_location) <= 5 km THEN 'Zone 1 - Free' WHEN ST_DISTANCE(warehouse_location, delivery_location) <= 15 km THEN 'Zone 2 - Standard' @@ -215,7 +216,7 @@ SELECT FROM orders WHERE order_date >= CURRENT_DATE AND ST_DISTANCE(warehouse_location, delivery_location) < 50 km -ORDER BY distance ASC +ORDER BY dist ASC ``` **14. Geofencing with meters:** @@ -224,7 +225,7 @@ SELECT device_id, user_name, timestamp, - ST_DISTANCE(POINT(48.8566, 2.3522), current_location) AS distance, + ST_DISTANCE(POINT(48.8566, 2.3522), current_location) AS dist, CASE WHEN ST_DISTANCE(POINT(48.8566, 2.3522), current_location) <= 50 m THEN 'Inside - Core' WHEN ST_DISTANCE(POINT(48.8566, 2.3522), current_location) <= 100 m THEN 'Inside - Buffer' @@ -269,10 +270,10 @@ SELECT airport_code, airport_name, city, - ST_DISTANCE(POINT(48.8566, 2.3522), location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), location) AS dist FROM airports WHERE ST_DISTANCE(POINT(48.8566, 2.3522), location) < 200 km -ORDER BY distance ASC +ORDER BY dist ASC LIMIT 5 ``` @@ -297,6 +298,10 @@ ORDER BY dist_from_paris ASC Creates a geo-point from latitude and longitude. +`POINT` has no standalone form: it is only accepted as an argument to `ST_DISTANCE`. Each +coordinate must be written with a decimal point — `POINT(1.0, 2.0)` is accepted, `POINT(1, 2)` is +not. Latitude comes first — **not** the GeoJSON order — in the WGS84 (EPSG:4326) reference system. + **Syntax:** ```sql POINT(latitude, longitude) @@ -315,37 +320,33 @@ POINT(latitude, longitude) **Examples:** -**1. Create a point:** +**1. Create a point** — `POINT` has no standalone form, so a point is written as an argument of +`ST_DISTANCE`: ```sql -SELECT POINT(48.8566, 2.3522) as paris_location --- Paris: 48.8566°N, 2.3522°E +SELECT id, ST_DISTANCE(location, POINT(48.8566, 2.3522)) AS from_paris +FROM stores +-- POINT(48.8566, 2.3522) is Paris: 48.8566°N, 2.3522°E ``` **2. Major world cities:** ```sql --- Paris, France -SELECT POINT(48.8566, 2.3522) as paris - --- London, UK -SELECT POINT(51.5074, -0.1278) as london - --- New York, USA -SELECT POINT(40.7128, -74.0060) as new_york - --- Tokyo, Japan -SELECT POINT(35.6762, 139.6503) as tokyo - --- Sydney, Australia -SELECT POINT(-33.8688, 151.2093) as sydney +-- Paris, France POINT(48.8566, 2.3522) +-- London, UK POINT(51.5074, -0.1278) +-- New York, USA POINT(40.7128, -74.0060) +-- Tokyo, Japan POINT(35.6762, 139.6503) +-- Sydney, Australia POINT(-33.8688, 151.2093) +SELECT name, ST_DISTANCE(location, POINT(51.5074, -0.1278)) AS from_london +FROM stores ``` **3. Use in distance calculation:** ```sql --- Distance between Paris and London -SELECT - ST_DISTANCE(POINT(48.8566, 2.3522), POINT(51.5074, -0.1278)) AS distance -WHERE ST_DISTANCE(POINT(48.8566, 2.3522), POINT(51.5074, -0.1278)) < 400 km --- Result: precomputed distance, approximately 343 km +-- Stores within 400 km of London, with their distance +SELECT + name, + ST_DISTANCE(location, POINT(51.5074, -0.1278)) AS from_london +FROM stores +WHERE ST_DISTANCE(location, POINT(51.5074, -0.1278)) < 400 km ``` **4. Use in WHERE clause:** @@ -365,11 +366,11 @@ SELECT name, address, phone, - ST_DISTANCE(POINT(48.8566, 2.3522), location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), location) AS dist FROM stores WHERE ST_DISTANCE(POINT(48.8566, 2.3522), location) <= 5 km AND open_now = true -ORDER BY distance ASC +ORDER BY dist ASC LIMIT 10 ``` @@ -379,11 +380,11 @@ SELECT name, cuisine, rating, - ST_DISTANCE(POINT(40.7128, -74.0060), location) AS distance + ST_DISTANCE(POINT(40.7128, -74.0060), location) AS dist FROM restaurants WHERE ST_DISTANCE(POINT(40.7128, -74.0060), location) <= 1 mi AND rating >= 4.0 -ORDER BY rating DESC, distance ASC +ORDER BY rating DESC, dist ASC LIMIT 20 ``` @@ -392,7 +393,7 @@ LIMIT 20 SELECT order_id, customer_name, - ST_DISTANCE(warehouse_location, delivery_location) AS distance, + ST_DISTANCE(warehouse_location, delivery_location) AS dist, CASE WHEN ST_DISTANCE(warehouse_location, delivery_location) <= 5 km THEN 'Local - Free Delivery' WHEN ST_DISTANCE(warehouse_location, delivery_location) <= 20 km THEN 'Regional - 5€' @@ -402,7 +403,7 @@ SELECT FROM orders WHERE order_date >= CURRENT_DATE AND ST_DISTANCE(warehouse_location, delivery_location) < 100 km -ORDER BY distance ASC +ORDER BY dist ASC ``` **4. Nearest Airport Search:** @@ -412,10 +413,10 @@ SELECT airport_name, city, country, - ST_DISTANCE(POINT(48.8566, 2.3522), location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), location) AS dist FROM airports WHERE ST_DISTANCE(POINT(48.8566, 2.3522), location) < 100 km -ORDER BY distance ASC +ORDER BY dist ASC LIMIT 5 ``` @@ -432,22 +433,14 @@ WHERE ST_DISTANCE(origin_location, destination_location) BETWEEN 50 nmi AND 200 ORDER BY distance_nmi ASC ``` -**6. Coverage Analysis by Store:** +**6. Coverage Analysis by Store:** a `JOIN` on a distance is **not** supported — the `ON` of a +`JOIN` must be an equality or an `AND` of equalities, so +`JOIN customers c ON ST_DISTANCE(s.location, c.location) <= 5 km` is refused. Compute each store's +coverage with one query per store, filtering the customers by their distance to it: ```sql -SELECT - s.store_id, - s.name as store_name, - s.city, - COUNT(DISTINCT c.customer_id) as customers_within_5km, - COUNT(DISTINCT CASE - WHEN ST_DISTANCE(s.location, c.location) <= 2 km - THEN c.customer_id - END) as customers_within_2km -FROM stores s -JOIN customers c ON ST_DISTANCE(s.location, c.location) <= 5 km -WHERE s.active = true -GROUP BY s.store_id, s.name, s.city -ORDER BY customers_within_5km DESC +SELECT COUNT(*) AS customers_within_5km +FROM customers +WHERE ST_DISTANCE(location, POINT(48.8566, 2.3522)) <= 5 km ``` **7. Real-time Geofencing:** @@ -456,7 +449,7 @@ SELECT device_id, user_name, timestamp, - ST_DISTANCE(POINT(48.8566, 2.3522), current_location) AS distance, + ST_DISTANCE(POINT(48.8566, 2.3522), current_location) AS dist, CASE WHEN ST_DISTANCE(POINT(48.8566, 2.3522), current_location) <= 50 m THEN 'Inside' WHEN ST_DISTANCE(POINT(48.8566, 2.3522), current_location) <= 100 m THEN 'Near' @@ -489,7 +482,7 @@ ORDER BY route_distance ASC SELECT order_id, customer_name, - ST_DISTANCE(warehouse_location, delivery_location) AS distance, + ST_DISTANCE(warehouse_location, delivery_location) AS dist, CASE WHEN ST_DISTANCE(warehouse_location, delivery_location) <= 10 km THEN 5.00 WHEN ST_DISTANCE(warehouse_location, delivery_location) <= 25 km THEN 10.00 @@ -499,7 +492,7 @@ SELECT FROM orders WHERE order_date >= CURRENT_DATE AND ST_DISTANCE(warehouse_location, delivery_location) < 100 km -ORDER BY distance ASC +ORDER BY dist ASC ``` **10. Proximity Search with Multiple Criteria:** @@ -599,23 +592,23 @@ The API supports comprehensive geo-spatial queries with distance calculations: -- Distance in kilometers SELECT name, - ST_DISTANCE(POINT(48.8566, 2.3522), location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), location) AS dist FROM stores WHERE ST_DISTANCE(POINT(48.8566, 2.3522), location) < 5 km -ORDER BY distance ASC +ORDER BY dist ASC -- Distance in miles SELECT name, - ST_DISTANCE(POINT(40.7128, -74.0060), location) AS distance + ST_DISTANCE(POINT(40.7128, -74.0060), location) AS dist FROM restaurants WHERE ST_DISTANCE(POINT(40.7128, -74.0060), location) <= 2 mi -ORDER BY distance ASC +ORDER BY dist ASC -- Distance range with BETWEEN SELECT name, - ST_DISTANCE(POINT(48.8566, 2.3522), location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), location) AS dist FROM stores WHERE ST_DISTANCE(POINT(48.8566, 2.3522), location) BETWEEN 4 km AND 10 km @@ -630,14 +623,14 @@ WHERE ST_DISTANCE(POINT(-70.0, 40.0), toLocation) BETWEEN 4000 km AND 5000 km -- Distance in nautical miles SELECT ship_name, - DISTANCE(port_location, ship_location) AS distance + DISTANCE(port_location, ship_location) AS dist FROM vessels WHERE DISTANCE(port_location, ship_location) < 50 nmi -- Distance in meters for precision SELECT device_id, - ST_DISTANCE(POINT(48.8566, 2.3522), current_location) AS distance + ST_DISTANCE(POINT(48.8566, 2.3522), current_location) AS dist FROM devices WHERE ST_DISTANCE(POINT(48.8566, 2.3522), current_location) < 100 m ``` diff --git a/documentation/sql/functions_math.md b/documentation/sql/functions_math.md index c11381534..c91584204 100644 --- a/documentation/sql/functions_math.md +++ b/documentation/sql/functions_math.md @@ -58,14 +58,13 @@ FROM orders; --- -#### SIGN / SGN +#### SIGN Returns -1, 0, or 1 according to sign. **Syntax:** ```sql SIGN(x) -SGN(x) ``` **Inputs:** @@ -88,8 +87,8 @@ SELECT SIGN(10) AS s; SELECT SIGN(0) AS s; -- Result: 0 --- Using SGN alias -SELECT SGN(-5.5) AS s; +-- A fractional value +SELECT SIGN(-5.5) AS s; -- Result: -1 -- Classify values @@ -396,9 +395,11 @@ CROSS JOIN ( ) AS avg_calc GROUP BY category; --- Euclidean distance (2D) +-- Squared Euclidean distance (2D), over dx DOUBLE SCRIPT AS (x2 - x1) and +-- dy DOUBLE SCRIPT AS (y2 - y1): an arithmetic expression is not accepted as a function argument, +-- so neither POWER(x2 - x1, 2) nor a SQRT over the sum parses SELECT - SQRT(POWER(x2 - x1, 2) + POWER(y2 - y1, 2)) AS distance + POWER(dx, 2) + POWER(dy, 2) AS dist_squared FROM coordinates; -- Calculate hypotenuse @@ -445,6 +446,9 @@ LOG(x) SELECT LOG(EXP(1)) AS l; -- Result: 1 +-- Natural log of 10 +SELECT LOG(10) AS l; +-- Result: 2.302585... -- Natural log of 1 SELECT LOG(1) AS l; @@ -592,7 +596,7 @@ COS(x) **Examples:** ```sql -- Cosine of π/3 (60 degrees) -SELECT COS(PI() / 3) AS c; +SELECT COS(RADIANS(60)) AS c; -- Result: 0.5 -- Cosine of 0 @@ -600,11 +604,11 @@ SELECT COS(0) AS c; -- Result: 1 -- Cosine of π/2 (90 degrees) -SELECT COS(PI() / 2) AS c; +SELECT COS(RADIANS(90)) AS c; -- Result: 0 (approximately) -- Cosine of π (180 degrees) -SELECT COS(PI()) AS c; +SELECT COS(PI) AS c; -- Result: -1 -- Convert degrees to radians and calculate @@ -672,7 +676,7 @@ SIN(x) **Examples:** ```sql -- Sine of π/6 (30 degrees) -SELECT SIN(PI() / 6) AS s; +SELECT SIN(RADIANS(30)) AS s; -- Result: 0.5 -- Sine of 0 @@ -680,11 +684,11 @@ SELECT SIN(0) AS s; -- Result: 0 -- Sine of π/2 (90 degrees) -SELECT SIN(PI() / 2) AS s; +SELECT SIN(RADIANS(90)) AS s; -- Result: 1 -- Sine of π (180 degrees) -SELECT SIN(PI()) AS s; +SELECT SIN(PI) AS s; -- Result: 0 (approximately) -- Convert degrees to radians @@ -712,19 +716,19 @@ ASIN(x) **Examples:** ```sql -- Arc sine of 0.5 -SELECT ASIN(0.5) AS as; +SELECT ASIN(0.5) AS a_sin; -- Result: 0.523598... (π/6 or 30 degrees) -- Arc sine of 1 -SELECT ASIN(1) AS as; +SELECT ASIN(1) AS a_sin; -- Result: 1.570796... (π/2 or 90 degrees) -- Arc sine of -1 -SELECT ASIN(-1) AS as; +SELECT ASIN(-1) AS a_sin; -- Result: -1.570796... (-π/2 or -90 degrees) -- Arc sine of 0 -SELECT ASIN(0) AS as; +SELECT ASIN(0) AS a_sin; -- Result: 0 -- Convert to degrees @@ -752,7 +756,7 @@ TAN(x) **Examples:** ```sql -- Tangent of π/4 (45 degrees) -SELECT TAN(PI() / 4) AS t; +SELECT TAN(RADIANS(45)) AS t; -- Result: 1 -- Tangent of 0 @@ -760,7 +764,7 @@ SELECT TAN(0) AS t; -- Result: 0 -- Tangent of π/6 (30 degrees) -SELECT TAN(PI() / 6) AS t; +SELECT TAN(RADIANS(30)) AS t; -- Result: 0.577350... (1/√3) -- Convert degrees to radians @@ -795,15 +799,15 @@ ATAN(x) **Examples:** ```sql -- Arc tangent of 1 -SELECT ATAN(1) AS at; +SELECT ATAN(1) AS a_tan; -- Result: 0.785398... (π/4 or 45 degrees) -- Arc tangent of 0 -SELECT ATAN(0) AS at; +SELECT ATAN(0) AS a_tan; -- Result: 0 -- Arc tangent of √3 -SELECT ATAN(SQRT(3)) AS at; +SELECT ATAN(SQRT(3)) AS a_tan; -- Result: 1.047197... (π/3 or 60 degrees) -- Convert to degrees @@ -880,34 +884,36 @@ Returns the value of π (pi). **Syntax:** ```sql -PI() +PI ``` +`PI` is a constant, written without parentheses: `PI()` does not parse. + **Output:** - `DOUBLE` (3.141592653589793) **Examples:** ```sql -- Value of π -SELECT PI() AS pi; +SELECT PI AS pi_value; -- Result: 3.141592653589793 -- Calculate circle area SELECT radius, - PI() * POWER(radius, 2) AS area + PI * POWER(radius, 2) AS area FROM circles; -- Calculate circle circumference SELECT radius, - 2 * PI() * radius AS circumference + 2 * PI * radius AS circumference FROM circles; -- Convert degrees to radians SELECT degrees, - degrees * PI() / 180 AS radians + degrees * PI / 180 AS radians FROM angles; ``` @@ -967,15 +973,15 @@ DEGREES(radians) **Examples:** ```sql -- Convert π radians to degrees -SELECT DEGREES(PI()) AS deg; +SELECT DEGREES(PI) AS deg; -- Result: 180 -- Convert π/2 radians to degrees -SELECT DEGREES(PI() / 2) AS deg; +SELECT DEGREES(RADIANS(90)) AS deg; -- Result: 90 -- Convert π/4 radians to degrees -SELECT DEGREES(PI() / 4) AS deg; +SELECT DEGREES(RADIANS(45)) AS deg; -- Result: 45 -- Convert result of ACOS to degrees @@ -989,9 +995,12 @@ SELECT DEGREES(ACOS(0.5)) AS angle_degrees; **1. Calculate Distance Using Pythagorean Theorem:** ```sql +-- dx DOUBLE SCRIPT AS (x2 - x1), dy DOUBLE SCRIPT AS (y2 - y1) in the table definition: an +-- arithmetic expression is not accepted as a function argument (see Known Limitations), so the +-- query answers the squared distance and its square root is taken from the returned rows SELECT point_id, - SQRT(POWER(x2 - x1, 2) + POWER(y2 - y1, 2)) AS distance + POWER(dx, 2) + POWER(dy, 2) AS dist_squared FROM coordinates; ``` @@ -1072,8 +1081,8 @@ ORDER BY price_bucket_start; SELECT circle_id, radius, - ROUND(2 * PI() * radius, 2) AS circumference, - ROUND(PI() * POWER(radius, 2), 2) AS area + 2 * PI * radius AS circumference, + PI * POWER(radius, 2) AS area FROM circles; ``` @@ -1093,16 +1102,16 @@ FROM circles; | `LOG(x)` | Natural log | `LOG(EXP(1))` → 1 | | `LOG10(x)` | Base-10 log | `LOG10(1000)` → 3 | | `EXP(x)` | e^x | `EXP(1)` → 2.718... | -| `COS(x)` | Cosine | `COS(PI()/3)` → 0.5 | +| `COS(x)` | Cosine | `COS(RADIANS(60))` → 0.5 | | `ACOS(x)` | Arc cosine | `ACOS(0.5)` → π/3 | -| `SIN(x)` | Sine | `SIN(PI()/6)` → 0.5 | +| `SIN(x)` | Sine | `SIN(RADIANS(30))` → 0.5 | | `ASIN(x)` | Arc sine | `ASIN(0.5)` → π/6 | -| `TAN(x)` | Tangent | `TAN(PI()/4)` → 1 | +| `TAN(x)` | Tangent | `TAN(RADIANS(45))` → 1 | | `ATAN(x)` | Arc tangent | `ATAN(1)` → π/4 | | `ATAN2(y, x)` | Two-arg arc tangent | `ATAN2(1, 1)` → π/4 | -| `PI()` | Value of π | `PI()` → 3.14159... | +| `PI` | Value of π | `PI` → 3.14159... | | `RADIANS(x)` | Degrees to radians | `RADIANS(180)` → π | -| `DEGREES(x)` | Radians to degrees | `DEGREES(PI())` → 180 | +| `DEGREES(x)` | Radians to degrees | `DEGREES(PI)` → 180 | --- diff --git a/documentation/sql/functions_system.md b/documentation/sql/functions_system.md index 3a4889216..7557168a0 100644 --- a/documentation/sql/functions_system.md +++ b/documentation/sql/functions_system.md @@ -6,7 +6,8 @@ ### Function: VERSION **Description:** -Return engine version string. +Not available: `VERSION()` is not a function of this engine, and `SELECT VERSION() AS v` is +rejected by the parser. **Inputs:** - none @@ -16,8 +17,8 @@ Return engine version string. **Example:** ```sql +-- rejected by the parser SELECT VERSION() AS v; --- Result: 'sql-elasticsearch-engine 1.0.0' ``` [Back to index](README.md) diff --git a/documentation/sql/known_limitations.md b/documentation/sql/known_limitations.md index ec3a2f2c6..2239da2fc 100644 --- a/documentation/sql/known_limitations.md +++ b/documentation/sql/known_limitations.md @@ -292,7 +292,10 @@ JOINs and correlated subqueries *inside* the branches that count, at any nesting ## Quoted identifiers — residual limits -Quoted column names, aliases and **table names** work in both spellings — see +Quoted column names, aliases and **table names** work in both spellings, in every statement — +`SELECT`, `DELETE`, `INSERT`, `UPDATE`, `CREATE`, `DROP`, `ALTER` and the rest +(``INSERT INTO `prod_eu`.dest``, ``UPDATE `orders` SET "a" = 1``, +`CREATE TABLE "dest" ("c" INTEGER)`) — see [Quoted identifiers](dql_statements.md#quoted-identifiers) and [Qualified and quoted table names](dql_statements.md#qualified-and-quoted-table-names), in every statement — `INSERT`, `UPDATE`, `CREATE`, `DROP` and `ALTER` included. Five things they do **not** diff --git a/documentation/sql/operator_precedence.md b/documentation/sql/operator_precedence.md index fa82bec92..a8a3acf66 100644 --- a/documentation/sql/operator_precedence.md +++ b/documentation/sql/operator_precedence.md @@ -47,11 +47,11 @@ SELECT 10 - 2 * 3 AS v1, -- Multiple levels SELECT ((5 + 3) * 2 - 4) / 2 AS result; --- Result: 6 +-- Result: 6.0 (`/` always yields a DOUBLE) -- Step 1: (5 + 3) = 8 -- Step 2: 8 * 2 = 16 -- Step 3: 16 - 4 = 12 --- Step 4: 12 / 2 = 6 +-- Step 4: 12 / 2 = 6.0 ``` **Best Practice:** @@ -195,7 +195,7 @@ FROM calendar; ```sql -- Multiplication and division (left to right) SELECT 10 * 2 / 4 AS result; --- Result: 5 (evaluated as (10 * 2) / 4 = 20 / 4) +-- Result: 5.0 (evaluated as (10 * 2) / 4 = 20 / 4) -- With modulo SELECT 17 % 5 * 2 AS result; @@ -579,8 +579,8 @@ SELECT (1 + 2) * 3 AS v; -- Complex calculation SELECT 10 + 5 * 2 - 8 / 4 AS result; --- Result: 18 --- Evaluation: 10 + (5 * 2) - (8 / 4) = 10 + 10 - 2 = 18 +-- Result: 18.0 +-- Evaluation: 10 + (5 * 2) - (8 / 4) = 10 + 10 - 2.0 = 18.0 ``` **Example 2: Comparison and Logical Operators** From cdb885db085bb1400d83493e9d4ef0c74a66e344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Manciot?= Date: Thu, 19 Nov 2026 08:23:42 +0100 Subject: [PATCH 3/3] docs(core): date, comparison and scalar rules as the engine answers them; examples that run Measured on Elasticsearch 8.18.3 and 6.8.23 with the engine at main: - A date result over aggregates (MAX(d) + 1, per group or over the whole table) answers its date or timestamp, no longer epoch milliseconds. - A date aggregate compared with a date literal in HAVING keeps the right groups since 0.24.0. - On Elasticsearch 6.8 a date column compared with another date column runs; a boolean literal cast to a number (CAST(TRUE AS INT)) fails to compile there, which Known Limitations and Version Compatibility now say. - A CASE used as an operand is one value; a simple CASE keeps its values' type; NULLIF compares a DATE with a quoted date in either shape. - An undeclared date field reported as TIMESTAMP since 0.24.0. - The HAVING key paragraph states what 0.24.0 changed (refused combinations), and the date aggregate note what 0.23 did (Elasticsearch failed the search). - Mathematical functions: examples the parser refuses (an arithmetic expression as a function argument) and examples Elasticsearch fails (a function result under an arithmetic operator, some functions nested over a column) are rewritten or removed; trigonometric results give the values returned; VERSION() no longer lists inputs and an output type. - Cherry-pick leftovers: a doubled sentence in the quoted identifiers limits, a watcher paragraph that repeated the block below it. Co-Authored-By: Claude Opus 5.5 --- documentation/sql/ddl_statements.md | 6 - documentation/sql/dql_statements.md | 23 +- documentation/sql/functions_conditional.md | 6 + documentation/sql/functions_math.md | 255 +++------------------ documentation/sql/functions_system.md | 6 - documentation/sql/known_limitations.md | 12 +- documentation/sql/operators.md | 21 +- 7 files changed, 75 insertions(+), 254 deletions(-) diff --git a/documentation/sql/ddl_statements.md b/documentation/sql/ddl_statements.md index 9b82cfb60..ad87effcb 100644 --- a/documentation/sql/ddl_statements.md +++ b/documentation/sql/ddl_statements.md @@ -1059,12 +1059,6 @@ FROM logs-*, metrics-* WHERE level = 'ERROR' WITHIN 5 MINUTES > > Pre-join the sources with a [`MATERIALIZED VIEW`](materialized_views.md) and point the watcher > at the view instead. -> -> **Table-qualified columns over a multi-index `FROM`** are rejected at parse time too: one search -> applies one query to *every* index it names, so it can neither join them -> (`FROM orders o, customers c WHERE o.id = c.order_id`) nor scope a predicate to one of them -> (`FROM orders, refunds WHERE orders.status = 'FAILED'`). `FROM logs-2025, logs-2024 WHERE -> level = 'ERROR'` is fine: no qualifier. A table alias may be used and is resolved in the `WHERE`, so `FROM orders o WHERE o.status = 'FAILED'` searches index `orders` for documents whose **`status`** field is `FAILED`. diff --git a/documentation/sql/dql_statements.md b/documentation/sql/dql_statements.md index f4e12c866..7483f323a 100644 --- a/documentation/sql/dql_statements.md +++ b/documentation/sql/dql_statements.md @@ -1648,18 +1648,17 @@ ORDER BY COUNT(*) DESC; #### Comparing a DATE aggregate -⚠️ **A comparison between a date aggregate and a date literal is refused**, function or not: -`HAVING MAX(created) > '2019-01-01'` and `HAVING MIN(created) < '2020-01-01'` are rejected at parse -time. A group filter reads every metric as a number — a date as epoch milliseconds — so the -generated comparison is text against a number and Elasticsearch fails the whole search with a -`class_cast_exception`. Compare in `WHERE` instead, or filter the result outside the query. +A date aggregate compares with a date literal as a date column does: `HAVING MAX(created) > +'2019-01-01'` keeps the groups whose latest `created` falls after that day, and +`HAVING MIN(created) < '2020-01-01'` those whose earliest falls before it (*since `0.24.0`*: +Elasticsearch failed the whole search, the comparison reading the date as text against a number). ### Conditions on the GROUP BY key A `HAVING` condition over the grouping key filters GROUPS, and it is applied by the `terms` filter — -so it is correct for a multi-valued field, where one document belongs to several groups. The rules -below hold since **0.24.0**; before it, several of the conditions now refused returned a -plausible-looking but wrong set of groups, without an error. +so it is correct for a multi-valued field, where one document belongs to several groups. Since **0.24.0**, a +condition the `terms` filter cannot apply as written is refused (see the combinations below); before +it, several of them returned a plausible-looking but wrong set of groups, without an error. ```sql SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city = 'Paris'; @@ -2147,7 +2146,7 @@ FROM dql_users; | `LEFT(str, n)` | Left n chars | | `RIGHT(str, n)` | Right n chars | | `REVERSE(str)` | Reverse string | -| `POSITION(substr IN str)` / `STRPOS(str, substr)` | 1-based position of substring | +| `POSITION(substr IN str)` | 1-based position of substring | ##### **Pattern matching:** @@ -2518,6 +2517,12 @@ the set operators other than `UNION ALL` need the relational engine wherever the of these versions alike. See [Known Limitations & Roadmap](known_limitations.md#which-forms-need-the-relational-engine). +On Elasticsearch 6.8, two forms still fail: a `GROUP BY` key that formats a bare date column +(`GROUP BY DATE_FORMAT(created_at, '%Y-%m')`) is refused by name, so truncate the column first; and a +boolean literal cast to a number (`CAST(TRUE AS INT)`) fails to compile in Elasticsearch. The same +formats in a `SELECT` or a `WHERE`, and a date column compared with another, run on 6.8. See +[Known Limitations & Roadmap](known_limitations.md). + --- ## Limitations diff --git a/documentation/sql/functions_conditional.md b/documentation/sql/functions_conditional.md index 6162eedc3..9d8e385e2 100644 --- a/documentation/sql/functions_conditional.md +++ b/documentation/sql/functions_conditional.md @@ -226,6 +226,8 @@ END **Output:** - Type coerced from result expressions (THEN/ELSE). +- Used as an operand, a `CASE` is one value: `CASE WHEN n > 0 THEN n ELSE 0 END + 1` adds 1 on every + branch, `4` for `n = 3` (*since `0.24.0`*: the operator applied to the last branch only, `3`). **Examples:** @@ -305,6 +307,8 @@ END **Output:** - Type coerced from result expressions. +- The values keep their own type: `CASE k WHEN 'a' THEN 0 ELSE 1 END` answers the numbers `0` and `1` + (*since `0.24.0`*: the text `"0"` and `"1"`). **Implementation notes:** The simple form evaluates by comparing `expr = value` for each WHEN. @@ -442,6 +446,8 @@ NULLIF(expr1, expr2) **Output:** - Type of `expr1` — a quoted literal first is the value it is read as beside `expr2`, and has its type: `NULLIF('2024-01-31', ts)` is a `TIMESTAMP`, `NULLIF('3', n)` a number — or NULL if equal +- A quoted date compares with a `DATE` in either shape: `NULLIF(d, '2024-01-31')` and + `NULLIF(d, '2024-01-31T00:00:00Z')` are both NULL on that day **Examples:** diff --git a/documentation/sql/functions_math.md b/documentation/sql/functions_math.md index c91584204..b4b7d1fd9 100644 --- a/documentation/sql/functions_math.md +++ b/documentation/sql/functions_math.md @@ -47,12 +47,11 @@ SELECT ABS(-123.456) AS a; SELECT * FROM transactions WHERE ABS(amount) > 1000; --- Calculate absolute difference -SELECT +-- Absolute difference, over price_gap DOUBLE SCRIPT AS (estimated_price - actual_price): an +-- arithmetic expression is not accepted as a function argument +SELECT order_id, - estimated_price, - actual_price, - ABS(estimated_price - actual_price) AS price_difference + ABS(price_gap) AS price_difference FROM orders; ``` @@ -177,18 +176,11 @@ SELECT ROUND(123.456, -1) AS r; -- Result: 120.0 (a DOUBLE operand gives a DOUBLE) -- Round prices -SELECT +SELECT product_id, price, - ROUND(price * 1.2, 2) AS price_with_tax + ROUND(price, 1) AS rounded_price FROM products; - --- Round averages -SELECT - category, - ROUND(AVG(price), 2) AS avg_price -FROM products -GROUP BY category; ``` --- @@ -225,21 +217,6 @@ SELECT FLOOR(5) AS f; -- Floor with decimals SELECT FLOOR(123.999) AS f; -- Result: 123 - --- Calculate age in complete years -SELECT - user_id, - name, - FLOOR(DATEDIFF(CURRENT_DATE, birth_date, DAY) / 365.25) AS age -FROM users; - --- Bucket values -SELECT - FLOOR(price / 10) * 10 AS price_bucket, - COUNT(*) AS count -FROM products -GROUP BY price_bucket -ORDER BY price_bucket; ``` --- @@ -278,13 +255,6 @@ SELECT CEILING(2.001) AS c; SELECT CEIL(5) AS c; -- Result: 5 --- Calculate required packages -SELECT - order_id, - total_items, - CEIL(total_items / 10.0) AS packages_needed -FROM orders; - -- Round up prices SELECT product_id, @@ -332,25 +302,9 @@ SELECT POWER(5, 2) AS square; SELECT POWER(3, 3) AS cube; -- Result: 27 --- Fractional exponent (root) -SELECT POWER(16, 0.5) AS p; --- Result: 4 (square root) - -- Negative exponent SELECT POWER(2, -3) AS p; -- Result: 0.125 (1/8) - --- Calculate compound interest -SELECT - initial_amount, - ROUND(initial_amount * POWER(1 + interest_rate, years), 2) AS final_amount -FROM investments; - --- Exponential growth -SELECT - day, - POWER(1.05, day) AS growth_factor -FROM generate_series(0, 10) AS day; ``` --- @@ -385,29 +339,11 @@ SELECT SQRT(2) AS s; SELECT SQRT(0) AS s; -- Result: 0 --- Calculate standard deviation component -SELECT - category, - SQRT(AVG(POWER(price - avg_price, 2))) AS std_dev +-- Standard deviation per category: SQRT(AVG(POWER(price - avg_price, 2))) does not parse (an +-- arithmetic expression is not accepted as a function argument), so use the aggregate itself +SELECT category, STDDEV_POP(price) AS std_dev FROM products -CROSS JOIN ( - SELECT AVG(price) AS avg_price FROM products -) AS avg_calc GROUP BY category; - --- Squared Euclidean distance (2D), over dx DOUBLE SCRIPT AS (x2 - x1) and --- dy DOUBLE SCRIPT AS (y2 - y1): an arithmetic expression is not accepted as a function argument, --- so neither POWER(x2 - x1, 2) nor a SQRT over the sum parses -SELECT - POWER(dx, 2) + POWER(dy, 2) AS dist_squared -FROM coordinates; - --- Calculate hypotenuse -SELECT - side_a, - side_b, - SQRT(POWER(side_a, 2) + POWER(side_b, 2)) AS hypotenuse -FROM triangles; ``` --- @@ -454,13 +390,6 @@ SELECT LOG(10) AS l; SELECT LOG(1) AS l; -- Result: 0 --- Calculate log returns -SELECT - date, - price, - LOG(price / LAG(price) OVER (ORDER BY date)) AS log_return -FROM stock_prices; - -- Logarithmic scale SELECT value, @@ -511,15 +440,6 @@ SELECT FLOOR(LOG10(ABS(value))) AS magnitude FROM measurements WHERE value != 0; - --- Logarithmic binning -SELECT - FLOOR(LOG10(population)) AS log_bucket, - COUNT(*) AS city_count -FROM cities -WHERE population > 0 -GROUP BY log_bucket -ORDER BY log_bucket; ``` --- @@ -557,19 +477,6 @@ SELECT EXP(2) AS e; -- Negative exponent SELECT EXP(-1) AS e; -- Result: 0.367879... - --- Calculate exponential growth -SELECT - time_period, - initial_value * EXP(growth_rate * time_period) AS projected_value -FROM projections; - --- Inverse of natural log -SELECT - x, - LOG(x) AS log_x, - EXP(LOG(x)) AS back_to_x -FROM values_table; ``` --- @@ -597,7 +504,7 @@ COS(x) ```sql -- Cosine of π/3 (60 degrees) SELECT COS(RADIANS(60)) AS c; --- Result: 0.5 +-- Result: 0.5000000000000001 (0.5, to floating-point rounding) -- Cosine of 0 SELECT COS(0) AS c; @@ -613,7 +520,7 @@ SELECT COS(PI) AS c; -- Convert degrees to radians and calculate SELECT COS(RADIANS(60)) AS c; --- Result: 0.5 +-- Result: 0.5000000000000001 (0.5, to floating-point rounding) ``` --- @@ -653,7 +560,7 @@ SELECT ACOS(0) AS ac; -- Convert result to degrees SELECT DEGREES(ACOS(0.5)) AS angle_degrees; --- Result: 60 +-- Result: 60.00000000000001 (60, to floating-point rounding) ``` --- @@ -677,7 +584,7 @@ SIN(x) ```sql -- Sine of π/6 (30 degrees) SELECT SIN(RADIANS(30)) AS s; --- Result: 0.5 +-- Result: 0.49999999999999994 (0.5, to floating-point rounding) -- Sine of 0 SELECT SIN(0) AS s; @@ -693,7 +600,7 @@ SELECT SIN(PI) AS s; -- Convert degrees to radians SELECT SIN(RADIANS(30)) AS s; --- Result: 0.5 +-- Result: 0.49999999999999994 (0.5, to floating-point rounding) ``` --- @@ -733,7 +640,7 @@ SELECT ASIN(0) AS a_sin; -- Convert to degrees SELECT DEGREES(ASIN(0.5)) AS angle_degrees; --- Result: 30 +-- Result: 30.000000000000004 (30, to floating-point rounding) ``` --- @@ -757,7 +664,7 @@ TAN(x) ```sql -- Tangent of π/4 (45 degrees) SELECT TAN(RADIANS(45)) AS t; --- Result: 1 +-- Result: 0.9999999999999999 (1, to floating-point rounding) -- Tangent of 0 SELECT TAN(0) AS t; @@ -769,14 +676,7 @@ SELECT TAN(RADIANS(30)) AS t; -- Convert degrees to radians SELECT TAN(RADIANS(45)) AS t; --- Result: 1 - --- Calculate slope -SELECT - rise, - run, - TAN(ATAN(rise / run)) AS slope_verified -FROM slopes; +-- Result: 0.9999999999999999 (1, to floating-point rounding) ``` --- @@ -813,13 +713,6 @@ SELECT ATAN(SQRT(3)) AS a_tan; -- Convert to degrees SELECT DEGREES(ATAN(1)) AS angle_degrees; -- Result: 45 - --- Calculate angle from slope -SELECT - rise, - run, - DEGREES(ATAN(rise / run)) AS angle_degrees -FROM slopes; ``` --- @@ -861,17 +754,6 @@ SELECT ATAN2(-1, -1) AS angle; -- Convert to degrees SELECT DEGREES(ATAN2(1, 1)) AS angle_degrees; -- Result: 45 - --- Calculate bearing/azimuth -SELECT - point_id, - DEGREES(ATAN2(delta_y, delta_x)) AS bearing_degrees -FROM coordinates; - --- Calculate angle between two points -SELECT - DEGREES(ATAN2(y2 - y1, x2 - x1)) AS angle -FROM point_pairs; ``` --- @@ -899,9 +781,9 @@ SELECT PI AS pi_value; -- Result: 3.141592653589793 -- Calculate circle area -SELECT +SELECT radius, - PI * POWER(radius, 2) AS area + PI * radius * radius AS area FROM circles; -- Calculate circle circumference @@ -950,7 +832,7 @@ SELECT RADIANS(45) AS rad; -- Use in trigonometric functions SELECT SIN(RADIANS(30)) AS sine_30_degrees; --- Result: 0.5 +-- Result: 0.49999999999999994 (0.5, to floating-point rounding) ``` --- @@ -986,106 +868,39 @@ SELECT DEGREES(RADIANS(45)) AS deg; -- Convert result of ACOS to degrees SELECT DEGREES(ACOS(0.5)) AS angle_degrees; --- Result: 60 +-- Result: 60.00000000000001 (60, to floating-point rounding) ``` --- ### Practical Mathematical Examples -**1. Calculate Distance Using Pythagorean Theorem:** -```sql --- dx DOUBLE SCRIPT AS (x2 - x1), dy DOUBLE SCRIPT AS (y2 - y1) in the table definition: an --- arithmetic expression is not accepted as a function argument (see Known Limitations), so the --- query answers the squared distance and its square root is taken from the returned rows -SELECT - point_id, - POWER(dx, 2) + POWER(dy, 2) AS dist_squared -FROM coordinates; -``` - -**2. Compound Interest Calculation:** -```sql -SELECT - account_id, - principal, - rate, - years, - ROUND(principal * POWER(1 + rate, years), 2) AS final_amount -FROM investments; -``` - -**3. Standard Deviation:** +**1. Standard Deviation:** ```sql -SELECT +SELECT category, - ROUND(SQRT(AVG(POWER(value - avg_value, 2))), 2) AS std_dev -FROM ( - SELECT - category, - value, - AVG(value) OVER (PARTITION BY category) AS avg_value - FROM measurements -) AS calc + STDDEV_POP(value) AS std_dev +FROM measurements GROUP BY category; ``` -**4. Normalize Values (0-1 range):** +**2. Calculate Circle Properties:** ```sql -SELECT - id, - value, - ROUND( - (value - MIN(value) OVER ()) / - (MAX(value) OVER () - MIN(value) OVER ()), - 4 - ) AS normalized_value -FROM data_table; -``` - -**5. Calculate Angle Between Vectors:** -```sql -SELECT - vector_id, - DEGREES(ATAN2(y, x)) AS angle_degrees, - SQRT(POWER(x, 2) + POWER(y, 2)) AS magnitude -FROM vectors; -``` - -**6. Exponential Moving Average:** -```sql -SELECT - date, - value, - ROUND( - value * EXP(-1 * days_diff / smoothing_factor), - 2 - ) AS ema_weight -FROM time_series; -``` - -**7. Price Buckets (Logarithmic):** -```sql -SELECT - POWER(10, FLOOR(LOG10(price))) AS price_bucket_start, - POWER(10, CEIL(LOG10(price))) AS price_bucket_end, - COUNT(*) AS product_count -FROM products -WHERE price > 0 -GROUP BY FLOOR(LOG10(price)), CEIL(LOG10(price)) -ORDER BY price_bucket_start; -``` - -**8. Calculate Circle Properties:** -```sql -SELECT +SELECT circle_id, radius, 2 * PI * radius AS circumference, - PI * POWER(radius, 2) AS area + PI * radius * radius AS area FROM circles; ``` +An arithmetic expression is not accepted as a function argument (`SQRT(POWER(x, 2) + POWER(y, 2))` +does not parse), and today a `POWER` or `ROUND` result under an arithmetic operator +(`POWER(dx, 2) + POWER(dy, 2)`, `PI * POWER(radius, 2)`, `ROUND(x, 1) * 2`) and some functions nested +over a column (`DEGREES(ATAN2(y, x))`, `EXP(LOG(x))`, `FLOOR(LOG10(x))`) fail in Elasticsearch: select +the parts and combine them from the returned rows. See +[Known Limitations](known_limitations.md#arithmetic-is-not-accepted-inside-a-function-a-cast-or-a-case-branch). + --- ### Mathematical Function Summary diff --git a/documentation/sql/functions_system.md b/documentation/sql/functions_system.md index 7557168a0..cd64d5a86 100644 --- a/documentation/sql/functions_system.md +++ b/documentation/sql/functions_system.md @@ -9,12 +9,6 @@ Not available: `VERSION()` is not a function of this engine, and `SELECT VERSION() AS v` is rejected by the parser. -**Inputs:** -- none - -**Output:** -- `VARCHAR` - **Example:** ```sql -- rejected by the parser diff --git a/documentation/sql/known_limitations.md b/documentation/sql/known_limitations.md index 2239da2fc..5ffe957ef 100644 --- a/documentation/sql/known_limitations.md +++ b/documentation/sql/known_limitations.md @@ -297,9 +297,8 @@ Quoted column names, aliases and **table names** work in both spellings, in ever (``INSERT INTO `prod_eu`.dest``, ``UPDATE `orders` SET "a" = 1``, `CREATE TABLE "dest" ("c" INTEGER)`) — see [Quoted identifiers](dql_statements.md#quoted-identifiers) and -[Qualified and quoted table names](dql_statements.md#qualified-and-quoted-table-names), in every -statement — `INSERT`, `UPDATE`, `CREATE`, `DROP` and `ALTER` included. Five things they do **not** -cover yet: +[Qualified and quoted table names](dql_statements.md#qualified-and-quoted-table-names). Five things +they do **not** cover yet: - **Quoting each part of a dotted index name splits it.** ``FROM `logs-2025`.`03` `` reads index `03` under the qualifier `logs-2025`, because a quoted part followed by a dot is a qualifier by @@ -490,6 +489,13 @@ As a **`GROUP BY` key**, such a format is refused by name on 6.8. Wrap the colum returns on 7+. See [DATE_FORMAT](functions_date_time.md#date_format) and [DATETIME_FORMAT](functions_date_time.md#datetime_format). +## A boolean literal cast to a number — Elasticsearch 6.8 fails it + +`CAST(TRUE AS INT)` fails on **Elasticsearch 6.8**, in a `SELECT` over an index and in a FROM-less +`SELECT` alike: Elasticsearch cannot compile the script it becomes (`(true ? 1 : 0)`), and the search +answers a `script_exception`. A boolean **column** cast to a number (`CAST(active AS INT)`) runs on +6.8, and so does `CASE WHEN active THEN 1 ELSE 0 END`. Elasticsearch 8 answers `1`. + ## Arithmetic is not accepted inside a function, a `CAST` or a `CASE` branch An arithmetic expression cannot be the **operand** of a function call, of a `CAST` or of a `CASE` diff --git a/documentation/sql/operators.md b/documentation/sql/operators.md index f8796736d..c6fec09b1 100644 --- a/documentation/sql/operators.md +++ b/documentation/sql/operators.md @@ -545,7 +545,8 @@ SELECT order_date * 2 FROM orders; client, or a field a bulk load added to a table elasticsql created — is a `TIMESTAMP`: `DESCRIBE TABLE` reports it so, a `CREATE TABLE ... AS SELECT` declares it so, and it follows the `TIMESTAMP` rules (`created_at + 1` keeps the time of day, `closed_at - opened_at` is - fractional). A column declared `DATE` through elasticsql stays a `DATE`. + fractional) (*since `0.24.0`*; it was a `DATE`). A column declared `DATE` through elasticsql stays + a `DATE`. - A string literal is read by what it is combined or compared with, as PostgreSQL reads one: `order_date - '2024-01-01'` is the days between two dates, `qty + '1'` adds the number 1, and in a comparison — `=`, `<>`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IN`, `CASE x WHEN v`, `NULLIF`, a @@ -579,21 +580,21 @@ SELECT order_date * 2 FROM orders; `SELECT order_date * 2` is refused. With no type to read (a field the indices of a pattern map with types a `UNION ALL` gives no common type), nothing is refused on types; a user who may not read the mapping is typed from `_field_caps` (*since `0.25.0`*). -- In a per-group calculation, a date result comes back as milliseconds since the epoch, the number - Elasticsearch computes it as; a date aggregate on its own (`MAX(order_date)`) answers its date or - timestamp. `CURRENT_DATE` and `NOW()` there are the time - the statement runs (`CURRENT_DATE - MAX(order_date)`); a materialized view refuses them. +- In a calculation over aggregates, per group or over the whole table, a date result answers its + date or timestamp, as a date aggregate on its own (`MAX(order_date)`) does: `MAX(order_date) + 1` + is a `DATE`, `MAX(created_at) + 1` a `TIMESTAMP` (*since `0.25.0`*: it came back as milliseconds + since the epoch, the number Elasticsearch computes it as). `CURRENT_DATE` and `NOW()` there are + the time the statement runs (`CURRENT_DATE - MAX(order_date)`); a materialized view refuses them. - An explicit cast applies to the result, and a `NULL` stays `NULL`: `(ship_date - order_date)::TIMESTAMP` converts the number of days as any number is converted to a `TIMESTAMP` — as milliseconds since the epoch — and `(quantity + ratio)::BIGINT` truncates, as `CAST(3.25 AS BIGINT)` does. - `INTERVAL` arithmetic (`order_date - INTERVAL 7 DAY`) and `DATEDIFF` / `TIMESTAMPDIFF` are unchanged. -- ⚠️ On Elasticsearch 6.8, a `date` column compared with another `date` column - (`WHERE ship_date > order_date`), or with a date function of one - (`WHERE ship_date > DATE_TRUNC(order_date, MONTH)`), fails with a 400 (`failed to parse date - field`); date arithmetic on one side runs: `WHERE ship_date > order_date + 0`. Elasticsearch 8 - answers all three. +- On Elasticsearch 6.8, a `date` column compared with another `date` column + (`WHERE ship_date > order_date`), with a date function of one + (`WHERE ship_date > DATE_TRUNC(order_date, MONTH)`) or with date arithmetic on one + (`WHERE ship_date > order_date + 0`) runs, as on Elasticsearch 8. **Before `0.24.0`:** `MAX(d) - MIN(d)` answered milliseconds and was typed `NUMERIC`; `+` and `-` with a date failed in Elasticsearch at row level — except a date plus a string, which concatenated