Search code examples
sparqlwikidata-query-service

How to count items with some property


Using https://query.wikidata.org I need to count the number of Q* items of Wikidata that have a statement with P402. Something like

SELECT (COUNT(?item) AS ?count) WHERE {?item wdt:P402.}

but, of course, it is an invalid query.


Solution

  • Your WHERE clause does not specify a valid basic triple pattern: an RDF triple consists of three items (subject, predicate, and object), where your pattern only contains two. Not knowing the Wikidata vocabulary too well, I'll assume that wdt:P402 is the predicate you're interested in. If that is case, your pattern is missing a variable or placeholder for the object of the triple pattern.

    To fix this, you could do something like this:

    SELECT (COUNT(?item) AS ?count) WHERE {?item wdt:P402 ?object.}
    

    Or (since you're not really interested in the value of the object), use a blank node instead:

    SELECT (COUNT(?item) AS ?count) WHERE {?item wdt:P402 [].}
    

    Finally, if you want to make sure that items which have more than one value for this property do not get counted more than once, you also need to add a DISTINCT clause to your query:

    SELECT (COUNT(DISTINCT ?item) AS ?count) WHERE {?item wdt:P402 [].}