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#
FILTERinside the braces restricts only the optional part. InOPTIONAL { ?city rdfs:label ?name FILTER (LANG(?name) = "hi") }a city without a Hindi label stays in the result, with?nameempty.- 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,?nameis 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 has a Hindi and an Arabic label, only an Arabic one, 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, would have an empty name. Without OPTIONAL (plain triple + FILTER for hi), only 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#
- Slides 01, p. 18 (single OPTIONAL), p. 19 (multiple OPTIONALs)
- ADIS_VL01 > OPTIONAL