GQL Essentials Algebra of Binding Tables
PDF ↗

Expressions and Algebra

Chapter 09Algebra of Binding Tables

This chapter introduces the algebra of binding tables, which forms the intermediate value domain on which query blocks and statements operate. We treat binding tables as bags of records and present selection, projection, joins, unwinding, and subquery composition as operations that transform them. The algebra is formulated with explicit bag semantics, three-valued logic, and ordering metadata, in a manner that aligns with the GQL standard’s treatment of optional pattern matching, correlation, and primitive result statements.

Classical bag-query algebras provide background on duplicates, aggregation, nesting, and expressive power (Grumbach and Milo 1996; Libkin and Wong 1997). They serve here only as mathematical background; binding-table descriptors, ordering metadata, preferred column names, and the operator rules remain governed by GQL.

9.1 Selection and Projection

Let T ∈BT be a binding table with bag(T) = ⟨τrec,B⟩. The formulas below act on this bag projection; each operator separately preserves or updates the ordered/unordered and preferred-column metadata of the complete binding-table descriptor. Projecting actions are modeled as functions on multisets of records:

  • Selection: σφ(BT) — the submultiset of records satisfying predicate φ (evaluated in GQL types, with null handling according to the comparison semantics and the three-valued truth tables from Chapter 8).
  • Projection: πE1↦n1,… ⁡,Ek↦nk(BT) — each input record occurrence contributes once to a new record r′ with fields named ni taking values ⟦Ei⟧(r); multiplicities of equal projected records are summed.
  • Natural join: BT1 ⋊⋉ BT2 — join based on name compatibility and equal values of shared fields; the bag multiplicity is consistent with the product of multiplicities of the paired records.
  • Ordering: ordering metadata may be included in the descriptor of a binding table, distinguishing ordered from unordered tables; it does not affect the underlying bag semantics but determines the order in which records are emitted.2

For example, let Tfees have the two rows

r1 = ⟨title↦’Graph DB 101’,late_fee↦0.0⟩, r2 = ⟨title↦’Graph Theory’,late_fee↦2.5⟩.

Then σlate_fee>0(Tfees) retains only r2, and projecting it onto title yields the singleton row ⟨title↦’Graph Theory’⟩.

9.2 Joins and OPTIONAL (Left-Outer Join)

Compatibility and merge. Mappings μ,ν are naturally compatible, written μ ∼ ν, iff their fields with the same name have equal values in the value-level sense used by the GQL definition of natural joinability. This is not an evaluation of the three-valued comparison predicate; in particular, two common fields that both contain the null value have equal values. Their merge μ ⊔ ν is the union partial map after any required common-type coercion and is well-defined when μ ∼ ν.

Binding-table semantics of OPTIONAL MATCH. Let BT be the current table, let Γ′ be a pattern, and let Δgpbt′ be its graph pattern binding table with an explicit or implicit YIELD clause. In ISO/IEC 39075, OPTIONAL MATCH is specified via a translation to an OPTIONAL CALL whose RETURN list contains only the new output bindings. The call is evaluated separately for every occurrence of an incoming record, so the correlation columns must not be projected away before the optional expansion.

More generally, let F be a correlated binding-table transformer and let Cnew be the columns in its declared output record type that are not columns of BT. For every occurrence of μ in BT, put

OutF(μ) := F({{μ}})(Cnew),

where the singleton is an incoming table occurrence and the final parentheses denote projection. Define the correlated optional expansion by

OptExpandF(BT) := ⊎ μ∈BT { ⊎ ν∈OutF(μ){μ ⊔ ν} if OutF(μ)≠∅, {μ ⊔{c↦null∣c ∈ Cnew}}otherwise.

Thus, with F = GPBTΔgpbt′, OPT_MATCHΓ′(BT) = OptExpandF(BT). This preserves correlation with each incoming record and fills all statically declared new fields with null exactly when that record has no matching extension.

Bag join. For bags B1,B2 of mappings, define the (natural) bag join

B1 ⋊⋉ B2 := ⊎ μ∈B1 ⊎ ν∈B2 { {μ ⊔ ν}if μ ∼ ν, ∅ otherwise.

Guarded join (ON-condition). Given a Boolean guard 𝜃, the guarded join is

B1 ⋊⋉ 𝜃B2 := filter𝜃(B1 ⋊⋉ B2),

where 𝜃 is evaluated over μ ⊔ ν. Note that U or ⊥ in 𝜃 discards the pair (no match), ⊤ ⁡ keeps it. If 𝜃 evaluates to err for some pair, the join is undefined (signals a dynamic exception).

Left outer join. Let hdr(B) be the set of variables in the declared record type of B, including when B is empty. Let πL project a merged mapping to the left variables hdr(B1), let ⊖ denote bag difference on these left projections, and let padR map each remaining left mapping μ to μ ⊔ η, where η binds every right-only variable in hdr(B2) ∖hdr(B1) to null. For B1,B2 and guard 𝜃, the left outer join is the bag

B1 ⊲𝜃 B2 := (B1 ⋊⋉ 𝜃B2) ⊎padR (B1 ⊖ πL (B1 ⋊⋉ 𝜃B2 )) ,

Denotational semantics of OPTIONAL MATCH. For a basic pattern P and an optional pattern Q with internal guard 𝜃 (e.g., a WHERE-predicate inside the optional clause), denotation is

⟦POPTIONAL(Q)⟧G = OptExpandFQ (⟦P⟧G) ,

where FQ({{μ}}) = ⟦Q⟧G,μ includes the internal guard 𝜃. A separate FILTER WHEREϕ after OPTIONAL is applied by filterϕ to the outer-join result (hence null-sensitive); a WHERE belonging to the optional graph pattern remains inside FQ.

OPTIONAL Block Denotation For a block consisting of a basic pattern P, an optional pattern Q with guard 𝜃, a separate trailing filter ϕ, and a projection s→, let projs→ denote the corresponding record projection, including evaluation of its expressions with the null-and-error semantics of Chapter 8 and preservation of bag multiplicities. Then

⟦MATCH POPTIONAL (Q)FILTER WHERE ϕRETURN s→⟧G = projs→ (filterϕ (OptExpandFQ (⟦P⟧G))) ,

9.3 FOR and List Unnesting

FOR on a list is modeled by unnestn:L(BT). For each occurrence of a record r ∈BT, if the field L contains the list (v1,… ⁡,vm), the operator produces the m records

r[n↦v1],… ⁡,r[n↦vm].

Under bag semantics, each generated record inherits the multiplicity of r; thus, multiplicities are multiplied when identical output records arise from different input occurrences or list positions. If L evaluates to null, no output record is generated for r.

9.4 Subqueries and Scope

A query block is a triple ⟨Γ, Φ,Π⟩:

  • Γ: (possibly empty) conjunction of graph/path patterns with a WHERE-predicate producing a base binding table as in Section 7.1.
  • Φ: a sequence of algebraic operators over binding tables (select, extend, join, unwind, group, distinct, order, slice).
  • Π: a final projection (RETURN-style) specifying visible columns and expressions to emit.

The grouping, ordering, and slicing stages are defined in Chapters 12 and 13. For a store state Ω, let BTΓ(Ω) denote the base binding table obtained by evaluating Γ in the working graph and correlation environment of Ω; for empty Γ, it is the unit binding table. The denotation of a block is

⟦⟨Γ, Φ,Π⟩⟧(Ω) = Π(Φ(BTΓ(Ω))).

Example (query-block decomposition). For the second query in Section 4.4, which computes total_late_fee, let Γfee denote its two path patterns together with the two ISBN conditions in their WHERE clause. In the abstraction above,

Φfee = σtotal_late_fee>0.0 ∘EXT(i1.late_fee+i2.late_fee)↦total_late_fee, Πfee = π l.loanid↦loanid, total_late_fee↦totalLateFee , QBfee = ⟨Γfee, Φfee,Πfee⟩.

Thus the graph-pattern WHERE belongs to Γfee; LET and the subsequent FILTER WHERE determine Φfee, while RETURN determines Πfee.

Linear-query pipelining. ISO/IEC 39075 does not use a WITH clause as a query-block boundary. Instead, the incoming and outgoing working record and working table types are threaded from each simple query statement to the next in a linear query statement. Projection and renaming are performed by the applicable result statement, and only the columns of its outgoing working table type are visible to a following statement.

Subqueries. A subquery evaluates to a binding table in the current Ω. When the subquery is correlated, references to names from the enclosing query are resolved in the current outer-row environment. The resulting binding table is consumed according to the surrounding evaluation context, as specified below for relational, scalar, and row-producing subqueries.

Environments and scopes. A static environment E maps names (variables, parameters, functions, and relevant catalog objects) to denotations. A dynamic environment Dyn provides the current graph G and the current outer-row mapping μo during correlated evaluation.

Uncorrelated subquery. A subquery Q that contains no reference to an outer binding is independent of the outer row. Its result is consumed according to its surrounding context; the additional static restrictions for a value query expression are stated below under scalar subqueries.

Correlated subquery. A subquery referencing outer attributes is a function of the outer row:

⟦Q⟧(μo) = ⟦Q⟧E,Dyn=(G,μo).

The EXISTS context consumes the resulting bag as follows:

EXISTS(Q)(μo) = { ⊤ ⁡if ⟦Q⟧(μo)≠∅, ⊥ otherwise.

Row-producing subqueries. In the FROM/pattern position, a subquery Q contributes its bag of rows to the surrounding algebra just like a base pattern.

Dynamic-context notation. In the formulas below, (G,μo) abbreviates the corresponding components of Dyn; function and procedure registries continue to be resolved through the static environment E. The outer mapping μo may be empty.

Variable hygiene. Each subquery has its own local variable namespace V loc disjoint from outer variables by α-renaming, except for explicitly correlated references to outer names, which are resolved in μo. Shadowing of names by aliases is disallowed unless explicitly stated.

Relational subqueries. A subquery Q used by an EXISTS predicate is evaluated as a bag BQ = ⟦Q⟧G,μo in environment (G,μo). Here μo is the current left-row mapping.

⟦EXISTS(Q)⟧G,μo tv = { ⊤ ⁡if BQ≠∅, ⊥if BQ = ∅

(never U); errors from inside the subquery propagate to the enclosing expression.

Scalar subqueries. A scalar subquery is a value query expression VALUE Q. Its nested query has a single result column, and its emitting RETURN is statically required either to use LIMIT 1 or to contain an aggregate without GROUP BY; hence its result has at most one record. Formally, with BQ = ⟦Q⟧G,μo:

⟦VALUE Q⟧G,μo = { nullif BQ = ∅, v if the sole field of the sole record of BQ has value v.

Subquery in OPTIONAL. When Q is correlated and appears on the right of OPTIONAL, the correlation uses the left-row mapping μ at the point of join; each μ yields ⟦Q⟧G,μ independently, composing via ⊲ as above.

9.5 Whole-Query Denotation

A full read-only query is a pipeline of blocks

Q = ⟨B1; B2; … ⁡; Bm⟩.

Each block is evaluated with respect to the fixed store state Ω and transforms the binding table produced by its predecessor. Let BT0 = BTunit, and, for 1 ≤ i ≤ m, define

BTi := ⟦Bi⟧(Ω; BTi−1).

The denotation of the complete query is therefore

⟦Q⟧(Ω) := BTm.

Equivalently,

⟦Q⟧(Ω) = ⟦Bm⟧(Ω; ⟦Bm−1⟧(Ω; ⋯⟦B1⟧(Ω; BTunit)⋯)).

Example (linear-query pipeline). The linear-composition query in Line 14 instantiates this recurrence with four successive transformations. Let Δgpbt,1 denote the first MATCH graph pattern together with its last-name WHERE predicate and its implicit YIELD clause, let Δgpbt,2 denote the corresponding graph pattern binding table for the second MATCH, and let

φ ≡i.due_date < DATE ’2025-12-31’

be the predicate of the subsequent FILTER WHERE. At the level of the abstraction above, Qlin = ⟨B1; B2; B3; B4⟩, where

BT1 = GPBTΔgpbt,1(BTunit), BT2 = GPBTΔgpbt,2(BT1), BT3 = σφ(BT2), BT4 = orderdue_date↑ (π l.loanid↦loanid,b.title↦title, i.due_date↦due_date,i.late_fee↦late_fee (BT3)) .

Here orderdue_date↑ denotes ascending ordering by the projected due_date field. Consequently, ⟦Qlin⟧(Ω) = BT4.

An updating statement is modeled separately because its evaluation may change the store state. Given an input binding table BT, its denotation has the form

⟦U⟧(Ω; BT) = ⟨Ω′,R⟩,

where Ω′ is the resulting store state and R is either a result binding table or an omitted result. When no preceding query blocks supply bindings to the update, BT is typically the unit binding table.

Soundness checks and algebraic laws (selected) Let ≡ denote bag-equivalence of binding tables (same records with same multiplicities, ignoring order). The following laws are intended only when every relevant expression evaluation yields the same value and raises no dynamic exception:

  • σφ1 (σφ2(BT) ) ≡σφ1∧φ2(BT).
  • πX (σφ(BT) ) ≡σφ|X (πX(BT) ) when φ mentions only X.
  • ⋊⋉ is associative and commutative up to field renaming and multiplicity algebra.
  • DISTINCT(DISTINCT(BT)) ≡DISTINCT(BT).

9.6 Composite Queries and Set Operators

A composite query combines the results of one or more linear query pipelines using set-like operators UNION, EXCEPT, INTERSECT and the fallback operator OTHERWISE. At the semantic level, a composite query expression denotes a binding table obtained by composing the binding tables produced by its constituent linear queries.

Syntactic shape. The grammar fragment

composite-query ::= query-part { query-conj query-part }

introduces a left-associative composition of query-parts. Each query-part is a linear-query. A query-conj is one of UNION, EXCEPT, INTERSECT, or OTHERWISE, with the set operators optionally qualified by a set quantifier ALL or DISTINCT. In line with the GQL standard, the following constraints are imposed:

  • If a set operator (UNION, EXCEPT, INTERSECT) is specified without an explicit set quantifier, the quantifier DISTINCT is implicit.
  • Within a single composite-query, all occurrences of query-conj must be the same query conjunction: the same operator and, for a set operator, the same ALL/DISTINCT choice after applying the implicit DISTINCT. Thus neither mixed operators such as UNION ... EXCEPT ... nor mixed quantifiers such as UNION ALL ... UNION DISTINCT ... are permitted.

Thus, each well-formed composite query expression has the form

Q0opQ1op… ⁡opQn

for a fixed query conjunction op, including its fixed set quantifier when applicable, and n ≥ 0, and is interpreted as left-associative:

(((Q0opQ1)opQ2)… ⁡opQn).

Typing and column combination. Each linear-query is a (possibly focused) linear query statement in the sense of the standard. We assume that evaluation of a linear query L produces a binding table TL = ⟦L⟧∈BT whose bag projection is

bag(TL) = ⟨τL,BL⟩,

where τL is a record type describing the columns and their value types, and BL is a finite multiset of records of type τL.

Let Q0,… ⁡,Qn be the query parts of a composite query, Ti = ⟦Qi⟧, and bag(Ti) = ⟨τi,Bi⟩ (these are the results of the immediately contained linear queries). Typing of the composite query is governed by the following constraints, mirroring Subclause 14.2:

  • All τi must be column name-equal: they have the same set of column names.
  • The τi must be column-combinable, in the sense of the type-combination relation: for each column name, the corresponding value types in τi admit a combined type, possibly a dynamic union type.
  • Let τ be the combined record type obtained from τ0,… ⁡,τn. The declared type of the composite query is the material binding table type with column type τ.

Operationally, each operand Ti = ⟦Qi⟧ can be coerced to the common type τ before applying the set operator, using the same coercion and dynamic-union rules as for column-combinable record types. When the operator is one of UNION DISTINCT, EXCEPT ALL, EXCEPT DISTINCT, INTERSECT ALL, INTERSECT DISTINCT, the standard additionally requires that no column in τ has a dynamic union type that mixes incomparable value types; otherwise, the composite query fails static validation. In these cases, every column acts as a grouping key, and the general grouping rules apply to the composite query.

Bag-based semantics of set operators. We now describe the algebraic semantics in terms of the binding-table algebra. Recall that a binding table is the descriptor-bearing object in BT fixed in Section 6.1. The equations below determine its bag projection ⟨τ,B⟩; the ordered/unordered indicator and preferred column-name sequence remain components of the complete result descriptor and are determined by the corresponding operation. Bag union is written B1 ⊎ B2, with multiplicities added element-wise.

For a binary composite expression of the form QLopqQR, where QL and QR denote, respectively, the left and right query part, with set operator

op ∈{UNION,EXCEPT,INTERSECT}

and quantifier q ∈{ALL,DISTINCT} (with DISTINCT as the default), let TL = ⟦QL⟧ and TR = ⟦QR⟧, with bag(TL) = ⟨τ,BL⟩ and bag(TR) = ⟨τ,BR⟩ after coercion to the common type τ. For any record r of type τ, write M = BL(r) and N = BR(r) for its multiplicities in the left and right operand (with M,N ≥ 0).

UNION ALL.

The result is the bag union

bag (⟦QLUNIONALLQR⟧) = ⟨τ,B⟩withB(r) = M + N.

This is the bag analog of GQL UNION ALL: duplicates from both operands are preserved, and their multiplicities added.

UNION (distinct).

The result is the set-union of the supports of the two bags:

B(r) = { 1if M + N > 0, 0otherwise.

Equivalently, ⟦QLUNIONQR⟧ is obtained by applying the DISTINCT operator to ⟦QLUNIONALLQR⟧.

EXCEPT ALL.

The result is bag difference:

B(r) = max ⁡ (M − N, 0).

Intuitively, duplicates of r in the right operand cancel duplicates in the left operand, but never below zero.

EXCEPT (distinct).

The result is set difference:

B(r) = { 1if M > 0 and N = 0, 0otherwise.

Equivalently, one can first apply DISTINCT to both operands and then form their EXCEPT ALL bag difference.

INTERSECT ALL.

The result is bag intersection:

B(r) = min ⁡ (M,N).

Each duplicate appears as many times as it is present in both operands.

INTERSECT (distinct).

The result is set intersection:

B(r) = { 1if M > 0 and N > 0, 0otherwise.

Again, this can be seen as INTERSECT ALL followed by DISTINCT.

For any of the distinct variants, and for EXCEPT ALL and INTERSECT ALL, if a record of the left operand and a record of the right operand are not comparable values, evaluation raises the data exception “values not comparable” (22G04) instead of producing a binding table.

Fallback semantics of OTHERWISE. The operator OTHERWISE is a fallback query conjunction rather than a set operator. For a binary composite

QLOTHERWISE QR,

where QL and QR denote the left and right operands, respectively, let TL = ⟦QL⟧ and TR = ⟦QR⟧, with

bag(TL) = ⟨τ,BL⟩andbag(TR) = ⟨τ,BR⟩,

where τ is their common combined type. Then

⟦QLOTHERWISEQR⟧ = { TLif BL≠∅, TRotherwise.

For a longer chain

Q0OTHERWISE Q1OTHERWISE ⋯OTHERWISE Qn,

the result is the binding table produced by the leftmost query operand whose result is non-empty, or the empty binding table of the combined type if all operands produce empty results. The same column-combination discipline as for the set operators applies; no duplicate elimination or bag arithmetic is performed. This describes result selection, not short-circuit evaluation: the General Rules for a composite query expression obtain the results of its query parts before choosing between them, so an operand is not skipped merely because an earlier result is non-empty.

Folding over multiple query parts. Let a composite query be written, after enforcing the uniform-operator rule, as

Q0opQ1op… ⁡opQn,

and let Comb_op,q be the binary operation on binding tables induced by the chosen operator and quantifier (one of the six set operations, or the OTHERWISE fallback). Then the denotation of the composite query is the left fold

⟦Q0op… ⁡opQn⟧ = Comb_op,q(… ⁡Comb_op,q(⟦Q0⟧,⟦Q1⟧),… ⁡,⟦Qn⟧).

This algebraic account is extensionally equivalent to the stepwise binding table construction described for the composite query expression in the GQL standard and provides a compact description of how composite queries act on the intermediate binding tables produced by linear query statements.

GQL Essentials · Dominik Tomaszuk

Search chapters, definitions and examples.