Joining patterns through shared variables

Multiple triple patterns join automatically.

0/2 done

Theory

Two patterns sharing a variable form an implicit join:

SELECT ?ninja ?master WHERE {
  ?ninja a :Ninja .
  ?master :teaches ?ninja .
}

The engine returns every (ninja, master) pair where the master teaches a known ninja.

Why it works: a row is kept only if every triple pattern matches with the same binding for any variable that appears more than once. In the example, ?ninja must be the same node in both patterns, which is exactly an inner join on ?ninja. Same idea in tabular form:

PatternBinds
?ninja a :Ninja .?ninja → every Ninja
?master :teaches ?ninja .+ ?master per pair

The vocabulary professionals use

A set of triple patterns joined this way is a Basic Graph Pattern (BGP) — the core unit SPARQL evaluation is defined on. Two facts about a BGP that matter in practice:

  • Pattern order doesn't change the result, only the speed. The join is commutative; rearranging patterns is a pure optimisation (put the most selective pattern first so the engine carries fewer intermediate bindings).
  • A join only happens on a bound shared variable. This is why OPTIONAL (next module) behaves differently: an unbound variable can't constrain the join, which is the source of the classic 'left-join explosion' bug.

Reading in progress · 0 of 2 activities done