Here is my naive query for bridges:

    ?item wdt:P31 wd:Q12280.  # Item's type is: bridge

Problem: It only returns a small fraction of all bridges, because railway bridges (and all other subclasses of "bridge") are not counted.

How to retrieve all items, including sub-classes/sub-sub-classes/etc?
It MUST be with SPARQL.

up vote 8 down vote accepted

The right expression to use here is p:P31/ps:P31/wdt:P279*.


  • p:P31/ps:P31 means instance of, or instance of not marked as preferred. Only using p:P31 at this step would miss some instance.
  • Following the "instance of" part, /wdt:P279* means this class or of any of its sub-classes/sub-sub-classes/etc

So, it means instance of this class or of any of its sub-classes/sub-sub-classes/etc.

The request becomes:

    ?item p:P31/ps:P31/wdt:P279* wd:Q12280.  # Item's type is: bridge or sub-type or sub-sub-type/etc

Try this query on

Something like

SELECT  ?item  ?type ?typeLabel WHERE {
    ?type (a | wdt:P279) wd:Q12280.  # Item's type is subclass of bridge
    ?item wdt:P31 ?type.
     SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
order by ?item

In this specific case it seems that all instances have a more specific type but may have multiple types. So you may want to `SELECT DISTINCT ?item.

Correct query

 {   ?type wdt:P279 wd:Q12280.  # Item's type is subclass of bridge 
     ?item wdt:P31 ?type. }
 { ?item wdt:P31 wd:Q12280.} # item is an instance of bridge 

DISTINCT required as entities may be instances of a bridge and one of its subclasses. Logically they all should be but apparently that's not how it's done in Wikidata.

  • 1
    I just noticed a problem. This seems to get only sub-classes (so, only railway bridge, suspended bridges, but not item that are simply bridges). How to include all? – Nicolas Raoul Sep 13 '16 at 9:20
  • 1
    The second query does not get sub-sub-classes, for instance Suspended wooden bridges. – Nicolas Raoul Apr 5 '17 at 10:31

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.