Skip to content

Expressions & Functions#

Typed SQL expression builders, aggregates, grouping sets, window functions, PostgreSQL full-text search, and JSONB / SQL-JSON helpers.

See Analytics Revenue Report, Keyset Pagination & Plans, and Column Types & DDL.


Core Expressions & Operators#

Expr#

signature
class Expr[T = PgValue](ExprBase, _ExprOpsMixin[T], ValueExpr[T]):
    def alias(self, name: str) -> Self: ...
    def filter(self, predicate: Expr[bool]) -> Self: ...
    def within_group(self, *order_by: OrderSpec | _Orderable) -> Self: ...
    def over(
        self,
        *,
        partition_by: Sequence[ExprArg] = (),
        order_by: Sequence[OrderSpec] = (),
        frame: WindowFrame | None = None,
    ) -> Self: ...
    def in_any(
        self, values: Sequence[T] | ParamRef[Sequence[T]] | ParamRef[list[T]] | UntypedParamRef
    ) -> Expr[bool]: ...

Typed SQL expression node backed by RustExpr. Supports Python comparison (==, !=, <, <=, >, >=), arithmetic (+, -, *, /), boolean (&, |, ~), aliasing (.as_(...)), ordering, and .over(...) window clauses. .in_(...) compiles to constant-shape = ANY($1).

OrderSpec#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class OrderSpec:
    column: str
    descending: bool = False
    nulls_first: bool = False
    nulls_last: bool = False
    table: str | None = None
    expr: RustExpr | None = None

Ordering specification produced by .asc(...) or .desc(...) on a Col or Expr, passed to Select.order_by(...), Index(...), or window/aggregate order_by=.

ParamRef#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class ParamRef[T = PgValue](ParamRefBase, ValueExpr[T]): ...

Named typed parameter placeholder returned by param(...) for use with prepare(...).

param#

signature
@overload
def param[T](name: str, py_type: TypeForm[T], *, pg_type: str | None = None) -> ParamRef[T]: ...

@overload
def param(name: str, py_type: None = None, *, pg_type: str | None = None) -> UntypedParamRef: ...

Declares a named bind parameter placeholder for prepare(...).

lit#

signature
def lit[T: PgValue](value: T, pg_type: str | None = None) -> Expr[T]: ...

Wraps a Python value as a bound SQL expression parameter.

col_ref#

signature
@overload
def col_ref[R: PgValue](name: str, *, table: str | None = None, returns: type[R]) -> Expr[R]: ...

@overload
def col_ref(name: str, *, table: str | None = None, returns: None = None) -> Expr[PgValue]: ...

Constructs an explicit column reference expression (e.g., referencing a CTE or lateral alias column by name).

func#

signature
@overload
def func[R: PgValue](
    name: str,
    *args: ExprArg,
    pg_type: str | None = None,
    order_by: Sequence[OrderSpec] = (),
    returns: type[R],
) -> Expr[R]: ...

@overload
def func(
    name: str,
    *args: ExprArg,
    pg_type: str | None = None,
    order_by: Sequence[OrderSpec] = (),
    returns: None = None,
) -> Expr[PgValue]: ...

Dynamic namespace for calling arbitrary PostgreSQL SQL functions (e.g., func.lower(Guest.email), func.date_trunc("day", Booking.created_at)).

cast#

signature
@overload
def cast[R: PgValue](
    value: ColBase | ExprBase | PgValue, pg_type: str, *, returns: type[R]
) -> Expr[R]: ...

@overload
def cast(
    value: ColBase | ExprBase | PgValue, pg_type: str, *, returns: None = None
) -> Expr[PgValue]: ...

Emits CAST(<expr> AS <pg_type>).

case#

signature
@overload
def case[R: PgValue](
    *whens: tuple[Expr[bool], TypedOperand[R]], else_: TypedOperand[R], pg_type: str | None = None
) -> Expr[R]: ...

@overload
def case[R: PgValue](
    *whens: tuple[Expr[bool], TypedOperand[R]], else_: UnsetType = UNSET, pg_type: str | None = None
) -> Expr[R | None]: ...

Emits a SQL CASE WHEN ... THEN ... ELSE ... END expression.

extract#

signature
def extract(field: ExtractField, source: ColBase | ExprBase | PgValue) -> Expr[Decimal]: ...

Emits EXTRACT(<field> FROM <source>).

now#

signature
def now() -> ServerDefaultExpr[datetime]: ...

Emits PostgreSQL now() returning TIMESTAMPTZ.

tuple_#

signature
@overload
def tuple_[T1: PgValue, T2: PgValue](
    c1: Col[T1] | Expr[T1], c2: Col[T2] | Expr[T2], /
) -> Expr[tuple[T1, T2]]: ...

@overload
def tuple_[T1: PgValue, T2: PgValue, T3: PgValue](
    c1: Col[T1] | Expr[T1], c2: Col[T2] | Expr[T2], c3: Col[T3] | Expr[T3], /
) -> Expr[tuple[T1, T2, T3]]: ...

@overload
def tuple_[T1: PgValue, T2: PgValue, T3: PgValue, T4: PgValue](
    c1: Col[T1] | Expr[T1],
    c2: Col[T2] | Expr[T2],
    c3: Col[T3] | Expr[T3],
    c4: Col[T4] | Expr[T4],
    /,
) -> Expr[tuple[T1, T2, T3, T4]]: ...

@overload
def tuple_(
    first: ColBase | ExprBase, second: ColBase | ExprBase, *rest: ColBase | ExprBase
) -> Expr[tuple[PgValue, ...]]: ...

Builds a SQL row-value tuple (a, b, ...) for keyset pagination comparisons (tuple_(Booking.created_at, Booking.booking_id) > (last_ts, last_id)). See Keyset Pagination & Plans.

and_#

signature
@overload
def and_(first: Expr[bool], /, *rest: Expr[bool] | None) -> Expr[bool]: ...

@overload
def and_(*exprs: Expr[bool] | None) -> Expr[bool] | None: ...

Combines boolean expressions with SQL AND.

or_#

signature
@overload
def or_(first: Expr[bool], /, *rest: Expr[bool] | None) -> Expr[bool]: ...

@overload
def or_(*exprs: Expr[bool] | None) -> Expr[bool] | None: ...

Combines boolean expressions with SQL OR.

coalesce#

signature
def coalesce[T: PgValue](
    first: ValueExpr[T | None] | ValueExpr[T], *rest: TypedOperand[T]
) -> Expr[T]: ...

Emits COALESCE(arg1, arg2, ...).

nullif#

signature
def nullif[T: PgValue](a: ValueExpr[T] | ValueExpr[T | None], b: TypedOperand[T]) -> Expr[T | None]: ...

Emits NULLIF(a, b).

greatest#

signature
def greatest[T: PgValue](first: ValueExpr[T] | T, *rest: TypedOperand[T]) -> Expr[T]: ...

Emits GREATEST(arg1, arg2, ...).

least#

signature
def least[T: PgValue](first: ValueExpr[T] | T, *rest: TypedOperand[T]) -> Expr[T]: ...

Emits LEAST(arg1, arg2, ...).


Aggregates & Grouping Sets#

count#

signature
def count(col: ColBase | ExprBase | None = None, *, distinct: bool = False) -> Expr[int]: ...

Emits count(*) (when col is None) or count([DISTINCT] <col>) [FILTER (WHERE <filter>)].

sum#

signature
@overload
def sum(col: Col[Decimal] | Expr[Decimal], *, distinct: bool = False) -> Expr[Decimal | None]: ...

@overload
def sum(col: Col[int] | Expr[int], *, distinct: bool = False) -> Expr[int | Decimal | None]: ...

@overload
def sum(col: Col[float] | Expr[float], *, distinct: bool = False) -> Expr[float | None]: ...

@overload
def sum(col: ColBase | ExprBase, *, distinct: bool = False) -> Expr[PgValue]: ...

Emits sum([DISTINCT] <col>).

avg#

signature
def avg(col: ColBase | ExprBase, *, distinct: bool = False) -> Expr[Decimal | None]: ...

Emits avg([DISTINCT] <col>).

min#

signature
def min[T: PgValue](col: ValueExpr[T]) -> Expr[T | None]: ...

Emits min(<col>).

max#

signature
def max[T: PgValue](col: ValueExpr[T]) -> Expr[T | None]: ...

Emits max(<col>).

array_agg#

signature
def array_agg[T: PgValue](
    expr: ValueExpr[T],
    *,
    distinct: bool = False,
    order_by: Sequence[OrderSpec] = (),
    filter: Expr[bool] | None = None,
) -> Expr[list[T] | None]: ...

Emits array_agg([DISTINCT] <expr> [ORDER BY ...]) [FILTER (WHERE ...)].

string_agg#

signature
def string_agg(
    expr: ValueExpr[str] | ValueExpr[str | None],
    sep: str | ValueExpr[str],
    *,
    distinct: bool = False,
    order_by: Sequence[OrderSpec] = (),
    filter: Expr[bool] | None = None,
) -> Expr[str | None]: ...

Emits string_agg([DISTINCT] <expr>, <sep> [ORDER BY ...]) [FILTER (WHERE ...)].

jsonb_agg#

signature
def jsonb_agg(
    expr: ExprArg,
    *,
    distinct: bool = False,
    order_by: Sequence[OrderSpec] = (),
    filter: Expr[bool] | None = None,
) -> Expr[JsonValue | None]: ...

Emits jsonb_agg([DISTINCT] <expr> [ORDER BY ...]) [FILTER (WHERE ...)].

bool_and#

signature
def bool_and(
    expr: ValueExpr[bool] | ValueExpr[bool | None], *, filter: Expr[bool] | None = None
) -> Expr[bool | None]: ...

Emits bool_and(<expr>) [FILTER (WHERE ...)].

bool_or#

signature
def bool_or(
    expr: ValueExpr[bool] | ValueExpr[bool | None], *, filter: Expr[bool] | None = None
) -> Expr[bool | None]: ...

Emits bool_or(<expr>) [FILTER (WHERE ...)].

percentile_cont#

signature
def percentile_cont(
    fraction: float | ValueExpr[float],
    *,
    order_by: OrderSpec | ColBase | Sequence[OrderSpec | ColBase],
) -> Expr[float | None]: ...

Emits the ordered-set aggregate percentile_cont(<fraction>) WITHIN GROUP (ORDER BY ...).

percentile_disc#

signature
def percentile_disc[T: PgValue](
    fraction: float | ValueExpr[float],
    *,
    order_by: OrderSpec | ColBase | Sequence[OrderSpec | ColBase],
) -> Expr[T | None]: ...

Emits the ordered-set aggregate percentile_disc(<fraction>) WITHIN GROUP (ORDER BY ...).

rollup#

signature
def rollup(first: ColBase | ExprBase, *rest: ColBase | ExprBase) -> GroupBySpec: ...

Produces a ROLLUP(...) grouping specification for Select.group_by(...). See Analytics Revenue Report.

cube#

signature
def cube(first: ColBase | ExprBase, *rest: ColBase | ExprBase) -> GroupBySpec: ...

Produces a CUBE(...) grouping specification for Select.group_by(...).

grouping_sets#

signature
def grouping_sets(*sets: Sequence[ColBase | ExprBase]) -> GroupBySpec: ...

Produces a GROUPING SETS ((...), ...) specification for Select.group_by(...).

grouping#

signature
def grouping(first: ColBase | ExprBase, *rest: ColBase | ExprBase) -> Expr[int]: ...

Emits PostgreSQL GROUPING(...) bitmask expression for distinguishing subtotal rows.

GroupBySpec#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class GroupBySpec:
    kind: GroupByKind
    sets: tuple[tuple[RustExpr, ...], ...]

Structured grouping-set specification returned by rollup(...), cube(...), and grouping_sets(...).


Window Functions & Frames#

row_number#

signature
def row_number() -> Expr[int]: ...

Emits row_number(). Chain with .over(...).

rank#

signature
def rank() -> Expr[int]: ...

Emits rank(). Chain with .over(...).

dense_rank#

signature
def dense_rank() -> Expr[int]: ...

Emits dense_rank(). Chain with .over(...).

lag#

signature
def lag[T: PgValue](
    col: ValueExpr[T],
    offset: int | None = None,
    default: TypedOperand[T] | None = None,
) -> Expr[T | None]: ...

Emits lag(<expr>, <offset>, <default>). Chain with .over(...).

lead#

signature
def lead[T: PgValue](
    col: ValueExpr[T],
    offset: int | None = None,
    default: TypedOperand[T] | None = None,
) -> Expr[T | None]: ...

Emits lead(<expr>, <offset>, <default>). Chain with .over(...).

first_value#

signature
def first_value[T: PgValue](col: ValueExpr[T]) -> Expr[T | None]: ...

Emits first_value(<expr>). Chain with .over(...).

last_value#

signature
def last_value[T: PgValue](col: ValueExpr[T]) -> Expr[T | None]: ...

Emits last_value(<expr>). Chain with .over(...).

WindowFrame#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class WindowFrame:
    units: FrameUnits = FrameUnits.ROWS
    start: FrameBound = FrameBoundKind.UNBOUNDED_PRECEDING
    end: FrameBound | None = FrameBoundKind.CURRENT_ROW

Window frame clause passed to Expr.over(frame=...).

FrameUnits#

signature
class FrameUnits(StrEnum):
    ROWS = "rows"
    RANGE = "range"
    GROUPS = "groups"

Window frame mode (ROWS, RANGE, or GROUPS).

FrameBound#

signature
type FrameBound = FrameBoundKind | tuple[int, FrameOffsetDir]

Start or end boundary of a WindowFrame.

rows_between#

signature
def rows_between(start: FrameBound, end: FrameBound | None = None) -> WindowFrame: ...

Constructs a ROWS BETWEEN <start> AND <end> window frame.

range_between#

signature
def range_between(start: FrameBound, end: FrameBound | None = None) -> WindowFrame: ...

Constructs a RANGE BETWEEN <start> AND <end> window frame.

groups_between#

signature
def groups_between(start: FrameBound, end: FrameBound | None = None) -> WindowFrame: ...

Constructs a GROUPS BETWEEN <start> AND <end> window frame.


to_tsvector#

signature
def to_tsvector(document: ExprArg, *, config: str | None = None) -> Expr[str]: ...

Emits to_tsvector([<config>, ]<document>).

to_tsquery#

signature
def to_tsquery(query: ExprArg, *, config: str | None = None) -> Expr[str]: ...

Emits to_tsquery([<config>, ]<query>).

plainto_tsquery#

signature
def plainto_tsquery(query: ExprArg, *, config: str | None = None) -> Expr[str]: ...

Emits plainto_tsquery([<config>, ]<query>).

phraseto_tsquery#

signature
def phraseto_tsquery(query: ExprArg, *, config: str | None = None) -> Expr[str]: ...

Emits phraseto_tsquery([<config>, ]<query>).

websearch_to_tsquery#

signature
def websearch_to_tsquery(query: ExprArg, *, config: str | None = None) -> Expr[str]: ...

Emits websearch_to_tsquery([<config>, ]<query>).

ts_rank#

signature
def ts_rank(vector: ExprArg, query: ExprArg) -> Expr[float]: ...

Emits ts_rank(<vector>, <query>).

ts_rank_cd#

signature
def ts_rank_cd(vector: ExprArg, query: ExprArg) -> Expr[float]: ...

Emits ts_rank_cd(<vector>, <query>) (cover-density ranking).


JSONB & SQL/JSON Helpers#

jsonb_path_exists#

signature
def jsonb_path_exists(
    target: ExprArg,
    path: str | ExprArg,
    *,
    vars: Mapping[str, JsonValue] | ExprBase | None = None,
    silent: bool | Expr[bool] | None = None,
) -> Expr[bool]: ...

Emits jsonb_path_exists(<target>, <path>[, <vars>[, <silent>]]).

jsonb_path_match#

signature
def jsonb_path_match(
    target: ExprArg,
    path: str | ExprArg,
    *,
    vars: Mapping[str, JsonValue] | ExprBase | None = None,
    silent: bool | Expr[bool] | None = None,
) -> Expr[bool]: ...

Emits jsonb_path_match(<target>, <path>[, <vars>[, <silent>]]).

jsonb_path_query_array#

signature
def jsonb_path_query_array(
    target: ExprArg,
    path: str | ExprArg,
    *,
    vars: Mapping[str, JsonValue] | ExprBase | None = None,
    silent: bool | Expr[bool] | None = None,
) -> Expr[list[JsonValue]]: ...

Emits jsonb_path_query_array(<target>, <path>[, <vars>[, <silent>]]).

jsonb_path_query_first#

signature
def jsonb_path_query_first(
    target: ExprArg,
    path: str | ExprArg,
    *,
    vars: Mapping[str, JsonValue] | ExprBase | None = None,
    silent: bool | Expr[bool] | None = None,
) -> Expr[JsonValue | None]: ...

Emits jsonb_path_query_first(<target>, <path>[, <vars>[, <silent>]]).

table_row#

signature
def table_row(target: TableRef) -> Expr[JsonObject]: ...

References a whole-row composite value (<table>) for use with row_to_json(...) or to_jsonb(...).

row_to_json#

signature
def row_to_json(target: type[Table] | TableAlias | ExprArg) -> Expr[JsonObject]: ...

Emits row_to_json(<target>).

to_jsonb#

signature
def to_jsonb(target: type[Table] | TableAlias | ExprArg) -> Expr[JsonValue]: ...

Emits to_jsonb(<target>).

json_object#

signature
def json_object(**fields: ExprArg) -> Expr[JsonObject]: ...

Emits SQL/JSON json_build_object(k1, v1, ...) from keyword pairs.