I am writing SPARQL queries on Wikidata entities, and I would like to get all the entities matching "is entity Q3 OR one of its subclasses".
I know how to get the subclasses only with the following query :
SELECT DISTINCT ?item
WHERE {
{ ?item wdt:P279 wd:Q3 . }
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
But I would like to also have the original parent entity (here Q3
) in the response. How should I modify my query so that Q3
is also returned ?
I ended up finding the solution myself :
I needed to add a ?
(which means "0 or 1") after the property in my query.
So it becomes :
SELECT DISTINCT ?item
WHERE {
{ ?item wdt:P279? wd:Q3 . } # here is the extra "?" after "wdt:P279"
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
And now this properly returns Q3 AND all of its subclasses.