4

Using the Wikidata SPARQL service, I would like to get the list of the 50 states and include the District of Columbia from Wikidata. I have come up with a kludgy query to do so:

#-- wdt:P31 = instance of;  wd:Q35657 = list of states

SELECT ?state ?stateLabel
   WHERE {
     {?state wdt:P31 wd:Q35657} UNION 
     {?state wdt:P3403 wd:Q3551781} . #-- coextensive with District of Columbia
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}

My query works but the way I extract DC into the results is ugly. (It's possible that future changes to data in Wikidata will break this query.) What I'd like to be able to say is something like

UNION {?state == wd:Q61}

to directly include Washington, D.C. (Q61). However, as a SPARQL newbie, I can't figure out the SPARQL syntax for doing so. I'd be grateful for any help to rewrite this query to directly pull in wd:Q61.

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
Raymond Yee
  • 549
  • 5
  • 13
  • 2
    You can use SPARQL 1.1 BIND, i.e. `{?state wdt:P31 wd:Q35657} UNION {BIND(wd:Q61 as ?state)}` to add fixed resources to the resultset. – UninformedUser Jan 24 '17 at 20:28

2 Answers2

8

You can use SPARQL 1.1 BIND to add fixed resources to the resultset, i.e.

SELECT ?state ?stateLabel WHERE {
     {?state wdt:P31 wd:Q35657} 
       UNION 
     {BIND(wd:Q61 as ?state)}
     SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
UninformedUser
  • 8,397
  • 1
  • 14
  • 23
  • Thanks -- this is the type of answer I'm looking for. I [confirm that it works](https://query.wikidata.org/#SELECT%20%3Fstate%20%3FstateLabel%0AWHERE%20%7B%0A%20%7B%3Fstate%20wdt%3AP31%20wd%3AQ35657%7D%20UNION%20%23%20wdt%3AP31%20%3D%20instance%20of%3B%20wd%3AQ35657%20%3D%20list%20of%20states%20%0A%20%20%20%20%20%7BBIND%28wd%3AQ61%20as%20%3Fstate%29%7D%20.%20%23%20add%20DC%0A%0A%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22%20%7D%0A%7D%0A%0A). – Raymond Yee Jan 24 '17 at 22:13
4

You could use an external identifier to uniquely identify Washington, D.C., if you're worried about the property that you're currently using being unstable.

For example, to use the Geonames ID for Washington, D.C. in your UNION statement, you could use the following:

# wdt:P31 = instance of;  wd:Q35657 = list of states; wdt:P1566 = Geonames ID

SELECT ?state ?stateLabel
   WHERE {
     {?state wdt:P31 wd:Q35657} UNION 
     {?state wdt:P1566 "4138106"} . # we want wd:Q61
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
Dan Scott
  • 76
  • 3
  • Your use of the Geonames ID is a good idea and an improvement on my query because it's less likely (not possible?) for more than one entity to share the same ID in Wikidata. Thank you for posting this solution. However, I'm still looking for way to refer to `wd:Q61` directly. Do you know how to do so? – Raymond Yee Jan 24 '17 at 19:45