Skip to content

UNION — alternative patterns ​

{ A } UNION { B } returns the solutions of A followed by the solutions of B. A variable that only one branch binds is null in rows produced by the other branch.

Examples use the sample data.

Example ​

sql
SELECT * FROM pgrdf.sparql($$
  PREFIX foaf: <http://xmlns.com/foaf/0.1/>
  SELECT ?p ?name ?mbox
  WHERE { { ?p foaf:name ?name }
          UNION
          { ?p foaf:mbox ?mbox } }
$$);
--  {"p": "http://example.org/alice", "mbox": null, "name": "Alice"}
--  {"p": "http://example.org/bob", "mbox": null, "name": "Bob"}
--  {"p": "http://example.org/carol", "mbox": null, "name": "Carol"}
--  {"p": "http://example.org/alice", "mbox": "mailto:alice@example.org", "name": null}
--  {"p": "http://example.org/carol", "mbox": "mailto:carol@example.org", "name": null}

Rows from the first branch carry ?name, rows from the second carry ?mbox. ?p appears in both branches, so every row has it.

Either of two properties ​

Bind the same variable in both branches to read "this property or that one" into one column:

sql
SELECT * FROM pgrdf.sparql($$
  PREFIX foaf: <http://xmlns.com/foaf/0.1/>
  PREFIX ex:   <http://example.org/>
  SELECT ?who ?contact
  WHERE { { ?who foaf:mbox ?contact }
          UNION
          { ?who ex:phone ?contact } }
  ORDER BY ?who
$$);
--  {"who": "http://example.org/alice", "contact": "mailto:alice@example.org"}
--  {"who": "http://example.org/carol", "contact": "mailto:carol@example.org"}

(Nobody in the sample data has an ex:phone, so only mailboxes come back.)

Combining with other features ​

  • Aggregates and GROUP BY work over a UNION.
  • Each branch can be scoped to a graph: { GRAPH <g1> { … } } UNION { GRAPH <g2> { … } } — see GRAPH.
  • A UNION inside OPTIONAL or inside MINUS is refused with an error. See OPTIONAL for a workaround.

pgRDF is released under the MIT license. Documentation built with VitePress, served via GitHub Pages.