Search code examples
sparqlwikidata

Wikidata SPARQL Query Filter Or


I'm trying to query Wikidata for all items that are an instance of business OR nonprofit organization.

The following works for one:

SELECT DISTINCT ?organization WHERE {
  ?organization wdt:P31 wd:Q4830453
}

But that doesn't retrieve all of them. Just all the businesses.

I have tried the following as well, but none seem to work.

SELECT DISTINCT ?organization WHERE {
  ?organization wdt:P31 wd:Q4830453 || wd:Q163740
}
SELECT DISTINCT ?organization WHERE {
  ?organization wdt:P31 wd:Q4830453, wd:Q163740
}

Of course I could just make two separate requests and combine them after the fact, but that doesn't seem as efficient and seems like there should be a better way to handle this.


Solution

  • Here is a working solution :

    SELECT * 
    WHERE {
        VALUES ?o { wd:Q4830453 wd:Q163740 } 
        ?s wdt:P31 ?o.
    }
    

    Be aware that the following query might also be a solution. However, FILTER a solution is never an efficient way to achieve something if another possibility exist.

    SELECT * 
    WHERE { 
        ?s wdt:P31 ?o.
        FILTER (?o IN (wd:Q4830453, wd:Q163740 ) )
    }