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
?aand the right binds?b, each result row has one of them bound and the other unbound — just like OPTIONAL. Project both and checkbound(). UNIONis a bag union — it does not remove duplicates; addSELECT DISTINCTif you need a set.- Prefer
VALUESor 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.