UNION — matching alternatives

Combine rows from two different patterns into one result.

0/2 done

Theory

UNION returns the rows that match either of two group patterns. Unlike a BGP (which intersects constraints), UNION adds solution sets together:

SELECT ?person WHERE {
  { ?person a :Ninja . }
  UNION
  { ?person a :Master . }
}

This returns everyone who is a ninja or a master. Key professional points:

  • Branches may bind different variables. If the left binds ?a and the right binds ?b, each result row has one of them bound and the other unbound — just like OPTIONAL. Project both and check bound().
  • UNION is a bag union — it does not remove duplicates; add SELECT DISTINCT if you need a set.
  • Prefer VALUES or a property-path alternative (|) for simple cases. { ?p a :Ninja } UNION { ?p a :Master } is often more cheaply written ?p a ?t . VALUES ?t { :Ninja :Master } — same answer, one BGP, easier for the planner.

Worked example — tag the matching branch

Worked example — union with branch-specific variables.

SELECT ?person ?role WHERE {
  { ?person a :Ninja .  BIND("ninja"  AS ?role) }
  UNION
  { ?person a :Master . BIND("master" AS ?role) }
}

Binding a literal tag per branch (?role) is the idiom for labelling which alternative matched — indispensable when the two branches mean different things downstream.

Reading in progress · 0 of 2 activities done