Built-in Functions Reference

Complete catalog of string, math, temporal, vector, geo, JSON, HSTORE, range, array, IP/CIDR, and ML scoring functions.

6 min read SpydQL & Data Modeling

SpydDB evaluates every scalar function natively inside the expression VM (and accelerates eligible numeric operators with native Cranelift JIT). Standard operators mirror both SpydQL and PostgreSQL Wire SQL.

Note: Dedicated full-text search and relevance functions (match, search, score, multi_match, fuzzy_match, phrase_match, highlight*, snippet*, rrf, hybrid_score) are documented in depth in the Full-Text Search & Hybrid Ranking manual.


1. String & Text Functions#

FunctionSignatureBehavior & Return Type
lower / upperlower(text) -> textASCII/UTF-8 lowercase or uppercase conversion
trim / ltrim / rtrimtrim(text) -> textStrips leading and/or trailing whitespace
lengthlength(text) -> i64Character length (null input returns null)
substringsubstring(text, start [, len]) -> text1-based character offset extraction (optional length)
left / rightleft(text, n) -> textFirst or last n characters (clamped to string length)
concatconcat(a, b, ...) -> textConcatenates values into text (skips null arguments, matching PostgreSQL)
replacereplace(text, from, to) -> textExact substring substitution
starts_with / ends_with / containsstarts_with(text, prefix) -> boolSubstring/affix predicate checks
contains_tokencontains_token(text, token) -> boolToken-boundary check using the full-text analyzer
domaindomain(email_or_url) -> textExtracts domain suffix from email or URL strings
tokenizetokenize(text) -> textDeterministic keyed pseudonymization token for dynamic field masking
like / not likecol like "prod-%"Linear-time % / _ wildcard matching
sql
users
| extend
    lower(trim(email)) as normalized,
    domain(email) as mail_domain,
    concat(left(first_name, 1), left(last_name, 1)) as initials
| where starts_with(normalized, "ada") and length(normalized) > 5
| pick id, normalized, mail_domain, initials;

2. Math, Finance & Control Flow#

FunctionDescription & Semantics
abs(x)Absolute value with checked overflow handling
round(x [, digits]), floor(x), ceil(x)Rounding & truncation for f64 and fixed-scale decimal
sqrt(x), power(base, exp)Checked floating-point power/root evaluation
greatest(a, b, ...), least(a, b, ...)Returns max/min across expressions
coalesce(a, b, ...)Returns first non-null value
nullif(a, b)Returns null when a == b, otherwise a
balance_delta(balance, min, max, delta)Checked bounded ledger arithmetic—errors if intermediate or resulting balance steps outside [min, max]

Example atomic bounded ledger update:

sql
accounts
| where id == 42
| set { balance_cents: balance_delta(balance_cents, 0, 10000000, -2500) }
| returning id, balance_cents;

3. Date, Time & Duration Functions#

Time literals support unquoted human duration suffixes: ns, us, ms, s, m, h, d, w (e.g., 15m, 1h, 7d).

FunctionSignatureDescription
now()-> timestampCurrent transaction UTC timestamp at microsecond resolution
time_bucket(ts, duration)-> timestampFloors instant to aligned bucket boundaries (e.g. time_bucket(created_at, 5m))
date_trunc(unit, ts)-> timestampTruncates to "second", "minute", "hour", "day", "week" (Monday-aligned), "month", "year"
extract(field, ts)-> i64Extracts "year", "month", "day", "hour", "minute", "second", "dow" (1..7), "doy" (1..366), or "epoch" (seconds)
sql
events
| where created_at >= now() - 24h
| extend date_trunc("hour", created_at) as hour_bucket, extract("dow", created_at) as dow
| group by hour_bucket
| agg count() as events
| sort hour_bucket asc;

4. JSON & HSTORE Functions#

JSON Navigation#

  • Inline path syntax: payload.customer.tier, payload.items[0].sku (0-based indexing inside dynamic JSON arrays)
  • json_get(doc, path): Extracts structured nested JSON value at a dot-separated path
  • json_text(doc, path): Extracts JSON scalar rendered cleanly as text (returns null when missing or JSON null)

HSTORE Key-Value Inspection#

FunctionSignatureReturn Type
hstore_get(map, key)Retrieves string value for key (or null)text
hstore_has_key(map, key)Checks whether key exists (even if its value is null)bool
hstore_keys(map)Returns all keystext[]
hstore_values(map)Returns all valuestext[]

5. Array Functions#

Typed arrays (text[], u64[], etc.) use 1-based indexing (arr[1]). Out-of-bounds or arr[0] evaluate to null.

FunctionDescription
array_length(arr)Number of elements (u64/i64) in arr (null if arr is null)
array_contains(arr, elem)Boolean membership check preserving typed equality rules

Combine with the unnest pipeline operator (| unnest tags as tag) to expand arrays into individual relational rows.


6. Range Functions#

Construct ranges ([lower, upper)) and query bounds without manual boundary math:

FunctionSignaturePurpose
int4range(lo, hi)-> int4rangeConstruct validated 32-bit signed integer range (lo <= hi)
int8range(lo, hi)-> int8rangeConstruct validated 64-bit signed integer range
daterange(lo, hi)-> daterangeConstruct validated calendar date range
tsrange(lo, hi)-> tsrangeConstruct validated microsecond timestamp range
range_contains(r, val)-> booltrue when val lies inside range bounds
range_overlaps(a, b)-> booltrue when two ranges of matching kind share any point
lower(r) / upper(r)-> scalarExtracts range lower or upper endpoint (null if unbounded)
is_empty(r)-> booltrue when the range encloses zero values

7. Vector & In-Engine ML Functions#

FunctionArguments & Purpose
nearest(col, vec, k)Exact top-k index/scan predicate pairing with vector(dim) collections
vector_distance(a, b)Euclidean L2 distance between two equal-length vectors
vector_similarity(a, b)Cosine similarity ([-1.0, 1.0])
vector_dot(a, b)Exact f64 dot product
vector_norm(a)L2 vector magnitude
vector_normalize(a)Returns unit-normalized vector
vector_centroid(a, b, ...)Element-wise mean vector across two or more vectors
sparse_dot(a, b)Inner product of two sparse_vector values
sparse_nearest(col, q, k)Top-k SPLADE Block-Max WAND sparse vector retrieval predicate
maxsim(doc_tokens, q_tokens)Exact ColBERT late-interaction MaxSim score (f64)
nearest_maxsim(col, q, k)Two-stage MUVERA FDE + exact MaxSim multi-vector top-k predicate
ml_score(model_json, feat1, ...)Deterministic in-engine linear/logistic/decision-list/GBDT/XGBoost/LightGBM inference score (f64)
ml_class(model_json, feat1, ...)Predicted class label (bool for binary classifiers, integer class index for multi-class GBDT)
ml_proba(model_json, feat1, ...)JSON array of class probabilities (softmax for multi-class GBDT, [1-p, p] for binary)
ml_explain(model_json, feat1, ...)Deterministic exact TreeSHAP JSON attribution (base_value, prediction, contributions, check_sum_error)
rrf(rank1, rank2 [, k])Reciprocal Rank Fusion score (default k = 60) for hybrid retrieval
hybrid_score(score1, score2 [, alpha])Weighted linear fusion (default alpha = 0.5)

Pair inference with the in-database training aggregates ml_train(features), ml_train_gbdt(features[, n_estimators[, max_depth]]), ml_train_gbdt_classifier(features[, n_estimators[, max_depth]]), and ml_train_gbdt_multiclass(features, num_classes[, n_estimators[, max_depth]]) (see Vector, Spatial, ML & Graph).


8. Geospatial Functions#

FunctionSignature & Behavior
geo_distance(p1, p2)Haversine great-circle distance in meters between two geo_point values
geo_within(pt, s, w, n, e)Axis-aligned latitude/longitude bounding-box check
geo_contains(poly, pt)Point-in-polygon check for geo_polygon shapes
geo_radius(pt, lat, lng, meters)Radius filter centered on (lat, lng) in meters
geo_near(pt, lat, lng, k)Spatial top-k nearest-neighbor scan predicate (R-Tree cell index accelerated)