query-1a82a662d135cd851b2fd2f5aba51d4b

rq turtle/ttl

Query returning countries where the largest city is not the capitalHello, . https://en.wikipedia.org/wiki/List_of_countries_whose_capital_is_not_their_largest_cityI am looking to write a query that basically builds this list I have tried multiple versions but I always get a timeout. What I have managed is to output the capital for each country with the capital's (most recent) population count. I think, I would need a subquery to get the most recent population count for each city. Then, for each country, I would have to determine the city with the highest such count and then check if it is not the capital. For the capital I would need another subquery to make sure it is the current capital (with the maximum start time). I would post my attempts here, but they are incredibly messy. Therefore, I just post my "starting point":

Use at

PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX ps: <http://www.wikidata.org/prop/statement/>
PREFIX pq: <http://www.wikidata.org/prop/qualifier/>
PREFIX p: <http://www.wikidata.org/prop/>
PREFIX bd: <http://www.bigdata.com/rdf#>
SELECT DISTINCT ?country ?countryLabel ?capital ?capitalLabel ?population1 WHERE {

  { SELECT ?capital (MAX(?date1) AS ?max_date1) WHERE {

    ?country p:P31/ps:P31 wd:Q6256 .

    ?country p:P36/ps:P36 ?capital . 

    ?capital p:P1082/pq:P585 ?date1 .

  } GROUP BY ?capital }

  ?country p:P31/ps:P31 wd:Q6256 .

  ?country p:P36/ps:P36 ?capital .

  ?capital p:P1082 ?p1 .

  ?p1 ps:P1082 ?population1 .

  ?p1 pq:P585 ?max_date1 .

  SERVICE wikibase:label {

     bd:serviceParam wikibase:language "en" .

  }

 } 

 ORDER BY ASC(?countryLabel)

Query found at

graph TD classDef projected fill:lightgreen; classDef literal fill:orange; classDef iri fill:yellow; v3("?capital"):::projected v2("?country"):::projected v1("?countryLabel"):::projected v4("?date1") v5("?max_date1") v6("?p1") v7("?population1"):::projected a1((" ")) a2((" ")) a3((" ")) a4((" ")) a5((" ")) c10(["bd:serviceParam"]):::iri c12(["en"]):::literal c3(["wd:Q6256"]):::iri v2 --"p:P31"--> a1 a1 --"p:statement/P31"--> c3 v2 --"p:P36"--> a2 a2 --"p:statement/P36"--> v3 v3 --"p:P1082"--> a3 a3 --"p:qualifier/P585"--> v4 bind1[/"max(?date1)"/] v4 --o bind1 bind1 --as--o v5 v2 --"p:P31"--> a4 a4 --"p:statement/P31"--> c3 v2 --"p:P36"--> a5 a5 --"p:statement/P36"--> v3 v3 --"p:P1082"--> v6 v6 --"p:statement/P1082"--> v7 v6 --"p:qualifier/P585"--> v5 subgraph s1["http://wikiba.se/ontology#label"] style s1 stroke-width:4px; c10 --"wikibase:language"--> c12 end