Study Vault Search notes, aliases and full text
Graph
ConceptADISAI-written · not yet proofread

Optional Graph Pattern

Also OPTIONAL · SPARQL OPTIONAL

`OPTIONAL { P }` in a SPARQL WHERE clause extends each result row with the bindings of pattern P where P matches, and keeps the row with P's new variables left empty where it doesn't.

Know these firstSPARQL Query Structure

Properties#

  • FILTER inside the braces restricts only the optional part. In OPTIONAL { ?city rdfs:label ?name FILTER (LANG(?name) = "hi") } a city without a Hindi label stays in the result, with ?name empty.
  • Several OPTIONALs act as fallbacks. They are applied in order. In the lecture query both OPTIONALs bind ?name. If the first one bound a Hindi label, the second can only match if that same value were an Arabic label, which is impossible, so it adds nothing. If the first one found no Hindi label, ?name is still unbound and the second may bind an Arabic label. Result: Hindi name, else Arabic name, else empty.
  • Order matters. Swapping the two OPTIONALs makes Arabic the preferred language and Hindi the fallback.

Example#

Toy data: city AA has a Hindi and an Arabic label, BB only an Arabic one, CC neither.

<A> rdfs:label "A-hi"@hi .
<A> rdfs:label "A-ar"@ar .
<B> rdfs:label "B-ar"@ar .
SELECT ?city ?name WHERE {
  ?city <type> <City> .
  OPTIONAL { ?city rdfs:label ?name FILTER (LANG(?name) = "hi") }
  OPTIONAL { ?city rdfs:label ?name FILTER (LANG(?name) = "ar") }
}
?city?name
<A>"A-hi"@hi
<B>"B-ar"@ar
<C>

With only the first OPTIONAL, BB would have an empty name. Without OPTIONAL (plain triple + FILTER for hi), only AA would be returned.

Lecture query (Slide 19): German cities with their Hindi name if they have one, and their Arabic name as fallback; cities with neither still appear.

Sources#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only