SPARQL/OPTIONAL

From Wikibooks, open books for an open world
Jump to navigation Jump to search
SELECT SPARQL
OPTIONAL
FILTER

With a triple ?person wdt:P569 ?birth_date the birth date of a person can be retrieved. But there might be occasions when a persons birth date is not known. In that case this triple acts as a selection: Only persons with birth dates are selected.

And that’s not what we want in this case: we primarily want to include this person and if additional data is available, we’d like to list that, but we don’t want that to limit our list of results.

The solution is to tell WDQS that those triples are OPTIONAL:

SELECT ?child ?childLabel ?genderLabel ?birth_date ?date_of_death
WHERE
{
  ?child wdt:P22 wd:Q76.# ?child  has father   Obama
  OPTIONAL{ ?child wdt:P21 ?gender. }
  OPTIONAL{ ?child wdt:P569 ?birth_date. }
  OPTIONAL{ ?child wdt:P570 ?date_of_death. }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY ?child

Try it!

Without OPTIONAL none of two the children of Obama would be shown, because the date of death is not filled for any of the children.

In general you should NOT include all optional triplets into one OPTIONAL { } sentence.

SELECT ?child ?childLabel ?genderLabel ?birth_date ?date_of_death
WHERE
{
  ?child wdt:P22 wd:Q76.# ?child  has father   Obama
  OPTIONAL{ ?child wdt:P21 ?gender.            # In general you should NOT include all optional triplets into one sentence   
            ?child wdt:P569 ?birth_date. 
            ?child wdt:P570 ?date_of_death. 
          }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY ?child

Try it!

The result is that all variables are blank when only one of them is missing in the data.

Cases where this might be useful is when the variables are tightly linked.


SELECT SPARQL
OPTIONAL
FILTER