Open main menu

Wikidata:SPARQL query service/Building a query/Museums on Instagram

A short, annotated guide to building a simple SPARQL query. Comments are preceded by a "#".

Step 1Edit

We start with a short & simple query, museums with Instagram username (P2003). Firstly, we SELECT (or display) some items, where instance of (P31) or subclass of (P279) is a type of museum (Q33506), AND those items have an Instagram username (P2003) We give the latter a label (not to be confused with the item's Wikidata label), ?instagram, so that we can refer to it later:

SELECT ?item WHERE {
  ?item wdt:P31/wdt:P279* wd:Q33506 . # The full stop (period) is required!
  ?item wdt:P2003 ?instagram . #Note that the label begins with a "?"
}
Try it!

Step 2Edit

That simply returns a list of "Q" IDs, so we modify it to show the name of the museum, by adding ?itemLabel to the SELECT line and invoking the "label" service:

SELECT ?item ?itemLabel WHERE {
  ?item wdt:P31/wdt:P279* wd:Q33506 .
  ?item wdt:P2003 ?instagram .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } . # "en" shows the labels in English
}
Try it!

Step 3Edit

But we also want to see the name of the Instagram account, so we add ?instagram (that's the label we chose in step one) to the SELECT line:

SELECT ?item ?itemLabel ?instagram WHERE {
  ?item wdt:P31/wdt:P279* wd:Q33506 .
  ?item wdt:P2003 ?instagram .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } .
}
Try it!

Step 4Edit

Museums are places, so let's also add their coordinate location (P625), which we will label as ?coordinates:

SELECT ?item ?itemLabel ?instagram ?coordinates WHERE {
  ?item wdt:P31/wdt:P279* wd:Q33506 .
  ?item wdt:P2003 ?instagram .
  ?item wdt:P625 ?coordinates .
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } .
}
Try it!

Note that we may get fewer results, as museums without coordinates are no longer shown.

Step 5Edit

Now we have the coordinates, we can see the museums on a map, by setting #defaultView:Map:

#defaultView:Map
SELECT ?item ?itemLabel ?instagram ?coordinates WHERE {
  ?item wdt:P31/wdt:P279* wd:Q33506 .
  ?item wdt:P2003 ?instagram .
  ?item wdt:P625 ?coordinates .
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } .
}
Try it!

Step 6Edit

We can rewrite this a bit to simplify — replacing two periods by semicolons and dropping the "subject", somewhat akin to how you could merge ordinary sentences in major natural languages:

#defaultView:Map
SELECT ?item ?itemLabel ?instagram ?coordinates WHERE {
  ?item wdt:P31/wdt:P279* wd:Q33506 ;
        wdt:P2003 ?instagram ;
        wdt:P625 ?coordinates .
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } .
}
Try it!

Step 7Edit