Wikidata:SPARQL query service/queries/examples

From Wikidata
Jump to navigation Jump to search
Other languages:
Bahasa Indonesia • ‎Bahasa Melayu • ‎Deutsch • ‎English • ‎Esperanto • ‎Nederlands • ‎Türkçe • ‎català • ‎dansk • ‎español • ‎français • ‎italiano • ‎lietuvių • ‎polski • ‎português do Brasil • ‎română • ‎svenska • ‎čeština • ‎беларуская (тарашкевіца) • ‎русский • ‎українська • ‎עברית • ‎العربية • ‎සිංහල • ‎中文 • ‎日本語 • ‎한국어

This page is parsed by the web interface of the query service to fill the query example dialog. Many of the examples also work in template:Wikidata list template calls parsed by the Listerbot, which however requires the ?item field variable to be selected.

Consider adding a comment in the query noting what it illustrates, when and by whom it was written and which are its limitations given the current data and use of properties at Wikidata.

Some queries did not fit here because of technical restrictions:

See also

Simple Queries

These basic queries help to understand SPARQL and the Wikibase RDF format.

Cats

SELECT ?item ?itemLabel 
WHERE 
{
  ?item wdt:P31 wd:Q146.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Try it!

Goats

SELECT ?item ?itemLabel 
WHERE 
{
  ?item wdt:P31 wd:Q2934.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Try it!


Horses (showing some info about them)

#Illustrates optional fields, instances of subclasses, language fallback on label service, date to year conversion
#Horses on Wikidata
SELECT DISTINCT ?horse ?horseLabel ?mother ?father (year(?birthdate) as ?birthyear) (year(?deathdate) as ?deathyear) ?genderLabel
WHERE
{
  ?horse wdt:P31/wdt:P279* wd:Q726 .     # Instance et sous-classes de Q726-Cheval
   
  OPTIONAL{?horse wdt:P25 ?mother .}       # P25  : Mère
  OPTIONAL{?horse wdt:P22 ?father .}       # P22  : Père
  OPTIONAL{?horse wdt:P569 ?birthdate .} # P569 : Date de naissance
  OPTIONAL{?horse wdt:P570 ?deathdate .}     # P570 : Date de décès
  OPTIONAL{?horse wdt:P21 ?gender .}       # P21  : Sexe
 
  SERVICE wikibase:label { #BabelRainbow
    bd:serviceParam wikibase:language "[AUTO_LANGUAGE],fr,ar,be,bg,bn,ca,cs,da,de,el,en,es,et,fa,fi,he,hi,hu,hy,id,it,ja,jv,ko,nb,nl,eo,pa,pl,pt,ro,ru,sh,sk,sr,sv,sw,te,th,tr,uk,yue,vec,vi,zh"
  }
}
ORDER BY ?horse

Try it!

Cats, with pictures

The following query uses these:

Features: ImageGrid (Q24515278)  View with Reasonator View with SQID

#defaultView:ImageGrid
SELECT ?item ?itemLabel ?pic
WHERE
{
?item wdt:P31 wd:Q146 .
?item wdt:P18 ?pic
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}

Map of hospitals

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#added 2017-08
#defaultView:Map
SELECT distinct * WHERE {
  ?item wdt:P31/wdt:P279* wd:Q16917;
        wdt:P625 ?geo .
}

Number of humans in Wikidata

Using the count function

SELECT (COUNT(*) AS ?count)
WHERE {
  ?item wdt:P31 wd:Q5 .
}

Try it!

Humans without children

In the simplest form:

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, child (P40)  View with Reasonator View with SQID
    #Demonstrates "no value" handling
    SELECT ?human ?humanLabel
    WHERE
    {
      ?human wdt:P31 wd:Q5 .       #find humans
      ?human rdf:type wdno:P40 .   #with at least one truthy P40 (child) statement defined to be "no value"
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
    }
    

A similar query which also gives non-truthy "no value" statements:

SELECT ?human ?humanLabel 
WHERE
{
  ?human wdt:P31 wd:Q5 .         #find humans
  ?human p:P40 ?childStatement . #with at least one P40 (child) statement
  ?childStatement rdf:type wdno:P40 .   #where the P40 (child) statement is defined to be "no value"
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" . }
}

Try it!

Humans born in New York City

This example highlights the correct way to use the P19 property and by extension the P20 property. P19 is most specific known place of birth. So for example it is known that Donald Trump (Q22686) was born in Jamaica Hospital (Q23497866). Therefore he wouldn't show up in the first query.

Incorrect way:

select distinct ?item ?itemLabel ?itemDescription ?sitelinks where {
    ?item wdt:P31 wd:Q5;  # Any instance of a human.
          wdt:P19 wd:Q60;  #  Who was born in New York City.
# Note. Doesn't include humans with the birth place listed as a hospital
# or an administrative area or other location of New York City.
# Only humans listed as born in New York City. 
             wikibase:sitelinks ?sitelinks.
   
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en,nl" }
}
ORDER BY DESC(?sitelinks)

Try it!

Correct way:

select distinct ?item ?itemLabel ?itemDescription ?sitelinks where {
    ?item wdt:P31 wd:Q5;  # Any instance of a human.
          wdt:P19/wdt:P131* wd:Q60;  #  Who was born in any value (eg. a hospital)
# that has the property of 'administrative area of' New York City or New York City itself.
             wikibase:sitelinks ?sitelinks.
   
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en,nl" }
}
ORDER BY DESC(?sitelinks)

Try it!

Items with a Wikispecies sitelink

#illustrates sitelink selection, ";" notation
SELECT ?item ?itemLabel ?article
WHERE
{
  ?article  schema:about ?item ;
      schema:isPartOf <https://species.wikimedia.org/> .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
LIMIT 200

Try it!

Items about authors with a Wikispecies page

SELECT ?author ?authorLabel (COUNT(?paper) AS ?count)
WHERE
{
  ?article  schema:about ?author ;
      schema:isPartOf <https://species.wikimedia.org/> .
    ?author wdt:P31 wd:Q5.
    ?paper wdt:P50 ?author.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
GROUP BY ?author ?authorLabel
ORDER BY DESC(?count)
LIMIT 200

Try it!

Recent Events

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, point in time (P585)  View with Reasonator View with SQID, start time (P580)  View with Reasonator View with SQID
    SELECT ?event ?eventLabel ?date
    WHERE
    {
      # find events
      ?event wdt:P31/wdt:P279* wd:Q1190554.
      # with a point in time or start date
      OPTIONAL { ?event wdt:P585 ?date. }
      OPTIONAL { ?event wdt:P580 ?date. }
      # but at least one of those
      FILTER(BOUND(?date) && DATATYPE(?date) = xsd:dateTime).
      # not in the future, and not more than 31 days ago
      BIND(NOW() - ?date AS ?distance).
      FILTER(0 <= ?distance && ?distance < 31).
      # and get a label as well
      OPTIONAL {
        ?event rdfs:label ?eventLabel.
        FILTER(LANG(?eventLabel) = "en").
      }
    }
    # limit to 10 results so we don't timeout
    LIMIT 10
    

Popular eye colors among humans

#illustrates bubblechart view, count

#defaultView:BubbleChart
SELECT ?eyeColorLabel (COUNT(?human) AS ?count)
WHERE
{
  ?human wdt:P31 wd:Q5.
  ?human wdt:P1340 ?eyeColor.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
GROUP BY ?eyeColorLabel

Try it!

Humans whose gender we know we don't know

The following query uses these:

  • Properties: sex or gender (P21)  View with Reasonator View with SQID
    # Demonstrates filtering for "unknown value"
    SELECT ?human ?humanLabel
    WHERE
    {
      ?human wdt:P21 ?gender .
      FILTER wikibase:isSomeValue(?gender)
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
    }
    

URLs of Wikipedia in all languages

This query provides an alternative to scraping the Wikipedia.org portal page and various lists/tables of Wikipedias that are out there. (The sitematrix API is another alternative.)

SELECT ?wikipedia WHERE {
  ?wikipedia wikibase:wikiGroup "wikipedia".
}

Try it!

Names of Wikipedia articles in multiple languages

The query retrieves Wikipedia article names (in the main namespace) in various languages for the given Q identity.

SELECT DISTINCT ?lang ?name WHERE {
  ?article schema:about wd:Q5 ;
              schema:inLanguage ?lang ;
              schema:name ?name ;
              schema:isPartOf [ wikibase:wikiGroup "wikipedia" ] .
  FILTER(?lang in ('en', 'uz', 'ru', 'ko')) .
  FILTER (!CONTAINS(?name, ':')) .
}

Try it!

All items with a property

# Sample to query all values of a property
# Property talk pages on Wikidata include basic queries adapted to each property
SELECT
  ?item ?itemLabel
  ?value ?valueLabel
# valueLabel is only useful for properties with item-datatype
WHERE 
{
  ?item wdt:P1800 ?value
  # change P1800 to another property        
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
# remove or change limit for more results
LIMIT 10

Try it!

Wikidata items of Wikipedia articles

#Returns a list of Wikidata items for a given list of Wikipedia article names
#List of Wikipedia article names (lemma) is like "WIKIPEDIA ARTICLE NAME"@LANGUAGE CODE with de for German, en for English, etc.
#Language version and project is defined in schema:isPartOF with de.wikipedia.org for German Wikipedia, es.wikivoyage for Spanish Wikivoyage, etc.

SELECT ?lemma ?item WHERE {
  VALUES ?lemma {
    "Wikipedia"@de
    "Wikidata"@de
    "Berlin"@de
    "Technische Universität Berlin"@de
  }
  ?sitelink schema:about ?item;
    schema:isPartOf <https://de.wikipedia.org/>;
    schema:name ?lemma.
}

Try it!

Total population in the Øresund Region

The following query uses these:

  • Properties: part of (P361)  View with Reasonator View with SQID, population (P1082)  View with Reasonator View with SQID, instance of (P31)  View with Reasonator View with SQID, has part (P527)  View with Reasonator View with SQID
    # by So9q, 2019-11-22
    # Total population in the Øresund Region
    # Example of the SUM aggregate function
    
    SELECT distinct ?area ?areaLabel (sum(?folkm_ngd) as ?total_folkm) # the first two variables can be removed
                                                                       # if only the number is needed
    WHERE {
      ?item wdt:P361 wd:Q297853.
      ?item wdt:P1082 ?folkm_ngd. 
      ?area wdt:P31 wd:Q1907114.
      ?area wdt:P527 ?item.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    }
    group by ?area ?areaLabel
    

Lexeme queries

Danish idioms

The following query uses these:

  • Items: Danish (Q9035)  View with Reasonator View with SQID, idiom (Q184511)  View with Reasonator View with SQID
    # Danish idioms
    # So9q 2021-04-11
    SELECT ?l ?lemma  WHERE {
      ?l dct:language wd:Q9035;
         wikibase:lemma ?lemma;
         wikibase:lexicalCategory wd:Q184511.
    }
    

All forms in Swedish missing a pronunciation for the form with a representation identical to the lemma of the lexeme

The following query uses these:

  • Properties: pronunciation audio (P443)  View with Reasonator View with SQID
    # All forms in Swedish missing a pronunciation for the form with a representation identical to the lemma of the lexeme
    # So9q 13-01-2021
    SELECT ?l ?lemma ?form ?audio WHERE {
      ?l dct:language wd:Q9027;
         wikibase:lemma ?lemma; 
         ontolex:lexicalForm ?form .
      ?form ontolex:representation ?lemma .
      minus {?form wdt:P443 ?audio.}
    }
    

Lexemes in English that match an expression

The following query uses these:

  • Items: English (Q1860)  View with Reasonator View with SQID
    # Lexemes in English that match an expression
    select ?lexemeId ?lemma WHERE {
      ?lexemeId dct:language wd:Q1860;
                wikibase:lemma ?lemma.
      # only those lemmas that begin with "pota", i.e. "potato"
      FILTER (regex(?lemma, '^pota.*'))
    }
    

Lexemes in Swedish with usage example that demonstrates both a form and a sense

The following query uses these:

  • Properties: usage example (P5831)  View with Reasonator View with SQID, demonstrates sense (P6072)  View with Reasonator View with SQID, demonstrates form (P5830)  View with Reasonator View with SQID
    #Lexemes in Swedish with usage example that demonstrates both a form and a sense
    # So9q 23-12-2020
    select ?lexemeId ?lemma ?example 
    WHERE {
      ?lexemeId <http://purl.org/dc/terms/language> wd:Q9027;
                wikibase:lemma ?lemma.
      ?lexemeId p:P5831 ?statement.
      ?statement ps:P5831 ?example;
                 pq:P6072 [];
                 pq:P5830 [].
    }
    

Pictures of noun lexemes in English (picture dictionary à la Wikidata)

The following query uses these:

Features: ImageGrid (Q24515278)  View with Reasonator View with SQID

# Lexemes in English with picture and description fetched from the concept Q-item
# NB: when 2 or more pictures occur for the same lemma a preferred rank is missing on the Q-item. 
# Please fix that if you know how.
# by So9q
#defaultView:ImageGrid
select distinct ?lexemeId ?lemma ?q_concept ?q_conceptDescription ?picture 
WHERE {
  ?lexemeId dct:language wd:Q1860;
            wikibase:lemma ?lemma;
            ontolex:sense ?sense.
  ?sense wdt:P5137 ?q_concept.
  ?q_concept wdt:P18 ?picture.
  # if you wish to only browse certain items you can insert a FILTER 
  # regular expression here, like in the example above.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
order by lcase(?lemma) # order a-z

German picture dictionary for young children

The following query uses these:

Features: ImageGrid (Q24515278)  View with Reasonator View with SQID

# German picture dictionary for young children
# NB: when 2 or more pictures occur for the same lemma a preferred rank is missing on the Q-item. 
# Please fix that if you know how.
# If any inapproriate terms show up it is probably because the sense is missing a correct P5137
# by So9q
#defaultView:ImageGrid
select distinct ?lexemeId ?lemma ?q_concept ?q_conceptDescription ?picture 
WHERE {
  ?lexemeId dct:language wd:Q188; # change language here
            wikibase:lemma ?lemma;
            ontolex:sense ?sense.
  ?sense wdt:P5137 ?q_concept.
  ?q_concept wdt:P18 ?picture.
  ############
  # Exclusions
  ############
  # Exclude out of scope concepts
  MINUS {?q_concept wdt:P31 wd:Q3624078.}. # countries
 
  # Exclude non suitable concepts
  VALUES ?minus {
  wd:Q47092 # rape
  wd:Q198   # war
  wd:Q124490 # violence
  wd:Q170382 # revolver
  wd:Q1576   #cigar
  #... add yours here
  }.
  MINUS {?sense wdt:P5137 ?minus.}.
  
  # Exclude senses not suitable for young children:
  VALUES ?filter {
  wd:Q8102
  wd:Q545779
  wd:Q1521634
  wd:Q184439}.
  FILTER NOT EXISTS {?sense wdt:P6191 ?filter.}.
  # if you wish to only browse certain items you can insert a FILTER 
  # regular expression here, like in the example above.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "de,en". }
}
order by lcase(?lemma) # order a-z

Lexeme languages by number of usage examples

The following query uses these:

Features: BubbleChart (Q24515280)  View with Reasonator View with SQID

# Lexeme languages by number of usage examples
# by Vesihiisi
# improved by So9q 23-20-2020 to only show those with both a form and a sense, 
# because that's what we really want 

#defaultView:BubbleChart
SELECT ?languageLabel (COUNT(?example) AS ?count ) WHERE {
  ?l a ontolex:LexicalEntry; dct:language ?language.
  ?l p:P5831 ?statement.
  ?statement ps:P5831 ?example;
             pq:P6072 [];
             pq:P5830 [].
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
GROUP BY ?languageLabel
ORDER BY DESC(?count)

Lexemes describing a color

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID
    # Lexemes describing a color
    # By Vesihiisi
    
    SELECT ?l ?lemma ?languageLabel  WHERE {
      ?l a ontolex:LexicalEntry; 
           dct:language ?language; 
           wikibase:lemma ?lemma .
      ?l wdt:P31 wd:Q376431.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    }
    ORDER BY ?languageLabel
    

Lexemes that means water ordered by language

The following query uses these:

  • Properties: item for this sense (P5137)  View with Reasonator View with SQID
    # By So9q
    # Lexemes that means (liquid) water
    select ?l ?sense ?lemma ?languageLabel WHERE {
      ?l a ontolex:LexicalEntry ; # get from the special LexicalEntry
           ontolex:sense ?sense ; # the sense
           dct:language ?language ; # the language
           wikibase:lemma ?lemma. # and the lemma
      ?sense wdt:P5137 wd:Q29053744 .
                       # change Q29053744 to anything you want 
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    }
    # Lower case before order
    order by (LCASE(?languageLabel))
    

The 100 most translated concepts in the Lexeme namespace

# by So9q, 2019-11-21
# no known limitations

#defaultView:BubbleChart
SELECT ?meaning ?meaningLabel (count(?l) as ?count) 
WHERE {
   ?l a ontolex:LexicalEntry ; 
        ontolex:sense ?sense. # get the sense
  ?sense wdt:P5137 ?meaning. #extract the meaning
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en"}
}
group by ?meaning ?meaningLabel # 2 here to avoid "bad aggregate", see https://www.wikidata.org/wiki/Wikidata:SPARQL_tutorial#Painting_materials
order by desc(?count) # rank by the most translated concepts 
limit 100 # only show the 100 highest to avoid clutter

Try it!

Demonyms on map

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

# Words describing people from a certain place
# e.g. swede
# by Vesihiisi
#defaultView:Map
SELECT ?l ?lemma ?demoPlaceLabel ?coords WHERE {
  ?l a ontolex:LexicalEntry ; 
       dct:language ?language ;
       wikibase:lemma ?lemma .
  ?language wdt:P218 'sv'. # language
  ?l ontolex:sense ?sense.
     ?sense wdt:P6271 ?demoPlace.
  ?demoPlace wdt:P625 ?coords
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Forms in Hebrew that are both feminine and masculine

The following query uses these:

  • Items: Hebrew (Q9288)  View with Reasonator View with SQID, noun (Q1084)  View with Reasonator View with SQID, masculine (Q499327)  View with Reasonator View with SQID, feminine (Q1775415)  View with Reasonator View with SQID
    # Forms of nouns in Hebrew that are both feminine and masculine
    # e.g. שמש
    # by Uziel302
    select ?lexemeId ?lemma ?form ?word WHERE {
      ?lexemeId dct:language wd:Q9288;
                wikibase:lexicalCategory wd:Q1084;
                wikibase:lemma ?lemma.
      ?lexemeId ontolex:lexicalForm ?form .
      ?form wikibase:grammaticalFeature wd:Q499327;
            wikibase:grammaticalFeature wd:Q1775415;
            ontolex:representation ?word .
    }
    

Wikibase predicates

Properties

Properties grouped by their parent property

#Properties grouped by their parent property
#TODO: should display links and numeric ids
#defaultView:Tree
SELECT ?property2 ?property2Label ?property1 ?property1Label WHERE {
  ?property1 rdf:type wikibase:Property. #not replaceable with wikibase:Item, wikibase:Statement, wikibase:Reference at WDQS
                                         #https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#WDQS_data_differences
  ?property1 wdt:P1647 ?property2.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Try it!

Subproperties of location (P276)

#Subproperties of location (P276)
SELECT DISTINCT ?subProperties ?subPropertiesLabel WHERE {
  ?subProperties wdt:P1647* wd:P276.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Try it!

Properties grouped by their Wikibase datatype (Q19798645) with number of properties

#Properties grouped by their type with number of properties
SELECT (COUNT(?property) as ?pcount ) ?wbtype WHERE {
  ?property rdf:type               wikibase:Property.
  ?property wikibase:propertyType  ?wbtype.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
GROUP BY ?wbtype
ORDER BY DESC(?pcount)

Try it!

Properties with value a technical standard (Q317623)

#Properties with value a technical standard
SELECT DISTINCT ?propertyRel ?propertyItem ?propertyItemLabel WHERE 
{
   ?item ?propertyRel ?standard.
   ?standard wdt:P31 wd:Q317623.
   ?propertyItem wikibase:directClaim ?propertyRel
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Try it!


All properties with descriptions and aliases and types

SELECT ?property ?propertyType ?propertyLabel ?propertyDescription ?propertyAltLabel WHERE {
  ?property wikibase:propertyType ?propertyType .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY ASC(xsd:integer(STRAFTER(STR(?property), 'P')))

Try it!

Properties connecting items of type zoo (Q43501) with items of type animal (Q729)

select ?p ?pLabel (count (*) as ?count) {
  ?s ?pd ?o .
  ?p wikibase:directClaim ?pd .
  ?s wdt:P31/wdt:P279* wd:Q729 .
  ?o wdt:P31/wdt:P279* wd:Q43501 .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} group by ?p ?pLabel order by desc(?count)

Try it!

Identifier properties present on one item, but absent on another

#added November 1, 2020 (76 ids then)
#TEMPLATE={ "template":"Identifiers present on the item for Penelope Cruz, but not on the item for Sean Connery"}
SELECT 
  ?p ?pLabel
  (SAMPLE(?url) as ?url_comp2)
WHERE
{
    hint:Query hint:optimizer "None".
    BIND( wd:Q4573 as ?comp1)
    BIND( wd:Q39666 as ?comp2)
    { 
        ?comp2 ?wdt ?v . 
        ?p wikibase:directClaim ?wdt ; wikibase:propertyType wikibase:ExternalId .
        FILTER NOT EXISTS { ?comp1 ?wdt [] }
        OPTIONAL { ?p  wdt:P1630 ?f }
        BIND(uri(REPLACE(?f,"\\$1",?v)) as ?url)
    }
    UNION { BIND(wd:Q4573 as ?p) }
    UNION { BIND(wd:Q39666 as ?p) }
   SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". } 
}
GROUP BY ?p ?pLabel
ORDER BY ?url_comp2

Try it!


References

Content of a reference for a specific statement

The following query uses these:

  • Properties: described by source (P1343)  View with Reasonator View with SQID, section, verse, paragraph, or clause (P958)  View with Reasonator View with SQID
    # See also the SPARQL manual
    # https://en.wikibooks.org/wiki/SPARQL/WIKIDATA_Qualifiers,_References_and_Ranks
    # In this example we look for statements which assign a specific value (Q51955019)
    # to the property P1343 and then look for references of that property, specifically
    # the string associated to P958 for the reference. May actually bring up references
    # for other P1343 statements; uses the shortened expression syntax with brackets.
    SELECT ?item ?reference
    WHERE {
      ?item wdt:P1343 wd:Q51955019 .
      ?item p:P1343 [ prov:wasDerivedFrom [ pr:P958 ?reference ] ] .
    }
    

Wikimedia projects

Sitelinks

Countries that have sitelinks to en.wiki

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID
    SELECT ?country ?countryLabel ?article WHERE {
    
        ?country wdt:P31 wd:Q3624078 . # sovereign state
        ?article schema:about ?country .
        ?article schema:isPartOf <https://en.wikipedia.org/>.
    
        SERVICE wikibase:label {
           bd:serviceParam wikibase:language "en"
        }
    }
    

Canadian subjects with no English article in Wikipedia

#added before 2019-02

SELECT ?item ?itemLabel ?cnt WHERE {
{
  SELECT ?item (COUNT(?sitelink) AS ?cnt) WHERE { 
  ?item wdt:P27|wdt:P205|wdt:P17 wd:Q16 . #Canadian subjects.
  minus {?item wdt:P106 wd:Q488111 .} #Minus occupations that would be inappropriate in most situations.
  minus {?item wdt:P106 wd:Q3286043 .}
  minus {?item wdt:P106 wd:Q4610556 .}  
  ?sitelink schema:about ?item .
  FILTER NOT EXISTS {
    ?article schema:about ?item .
    ?article schema:isPartOf <https://en.wikipedia.org/> . #Targeting Wikipedia language where subjects has no article.
  }
  } GROUP BY ?item ORDER BY DESC (?cnt) LIMIT 1000 #Sorted by amount of articles in other languages. Result limited to 1000 lines to not have a timeout error.
}
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en,fr,es,de" }  #Service to resolve labels in (fallback) languages: automatic user language, English, French, Spanish, German.
} ORDER BY DESC (?cnt)

Try it!

Countries that have a Featured Article on Russian Wikipedia

SELECT ?sitelink ?itemLabel WHERE {
  ?item wdt:P31 wd:Q6256.
  ?sitelink schema:isPartOf <https://ru.wikipedia.org/>;
     schema:about ?item;
     wikibase:badge wd:Q17437796 . # Sitelink is badged as a Featured Article
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" } .
} ORDER BY ?itemLabel

Try it!

Numbers of Wikipedia sitelinks for items with Art UK artist ID (P1367) for each language

SELECT ?lang (COUNT(DISTINCT ?article) AS ?count) WHERE {
  hint:Query hint:optimizer "None".
  ?item wdt:P1367 ?yp_id .
  ?article schema:about ?item . # find articles about things with a BBC 'Your paintings' artist identifier
  ?article schema:isPartOf / wikibase:wikiGroup "wikipedia" . # only Wikipedias articles
  hint:Prior hint:gearing "forward" .
  # This hint says to search the property chain above from left to right ("forward"),
  # i.e. it is checked if each previously found value for ?article is linked to a Wikipedia.
  # The default ("reverse") would be to search it from right to left, i.e. find all Wikipedia
  # articles first, and then select the intersection with the previously found values of ?article.
  ?article schema:inLanguage ?lang .
} GROUP BY ?lang
ORDER BY DESC (?count)

Try it!

Titles of articles about Ukrainian villages on Romanian Wikipedia

#Show titles of articles about Ukrainian villages on Romanian Wikipedia, plus English and Ukrainian labels in Wikidata items
#added in 2017-05
SELECT DISTINCT ?item ?LabelEN ?LabelUK ?page_titleRO WHERE {
  ?item wdt:P31 wd:Q532 .  
  ?item wdt:P17 wd:Q212 .
  ?article schema:about ?item ; schema:isPartOf <https://ro.wikipedia.org/> ;  schema:name ?page_titleRO .
  ?item rdfs:label ?LabelEN filter (lang(?LabelEN) = "en") .
  ?item rdfs:label ?LabelUK filter (lang(?LabelUK) = "uk") .
}
LIMIT 300

Try it!

Wikisource pages for authors of scientific articles

#Wikisource pages for authors of scientific articles, ordered by Wikisource language
#added in 2017-09
SELECT DISTINCT ?item ?wikisourceSitelink ?wikisourceLanguage WHERE {
  ?wikisourceSitelink schema:isPartOf [ wikibase:wikiGroup "wikisource" ];
                      schema:inLanguage ?wikisourceLanguage;
                      schema:about ?item.
  ?paper wdt:P31 wd:Q13442814;
         wdt:P50 ?item.
}
ORDER BY ?wikisourceLanguage
LIMIT 300

Try it!

Items with a GTAA id and their articles on the Dutch and English Wikipedia

select ?item ?itemLabel ?gtaa ?_articleEN ?_articleNL where {
  ?item wdt:P1741 ?gtaa. # GTAA id
  OPTIONAL {
    ?_articleEN schema:about ?item.
    ?_articleNL schema:about ?item.
    ?_articleEN schema:isPartOf <https://en.wikipedia.org/>.
    ?_articleNL schema:isPartOf <https://nl.wikipedia.org/>.
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en,nl". }
}

Try it!

People deceased in 2018 ordered by the number of sitelinks

select ?person ?personLabel ?died ?sitelinks where {
  ?person wdt:P31 wd:Q5;
          wdt:P570 ?died.
  filter (?died >= "2018-01-01T00:00:00Z"^^xsd:dateTime && ?died < "2019-01-01T00:00:00Z"^^xsd:dateTime)
  ?person wikibase:sitelinks ?sitelinks.
  service wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}  order by desc(?sitelinks) limit 100

Try it!

List of small monuments with link to Commons category (either from sitelink and P373)

SELECT ?item ?comm ?p373 ?cat WHERE {
  ?item wdt:P131* wd:Q894107.                               # ... municipality ...

  optional {?comm schema:about ?item ; schema:isPartOf <https://commons.wikimedia.org/> .}
  BIND(replace(wikibase:decodeUri(SUBSTR(STR(?comm), 45)),"_"," ") AS ?comm_decode)
   optional {?item wdt:P373 ?p373 .}
  
 bind(COALESCE(?comm_decode, ?p373) as ?cat) .
 VALUES ?trida { wd:Q1746392 wd:Q108325 wd:Q4989906 wd:Q10861631 wd:Q15077340 wd:Q1516537 wd:Q47008262}     # chapel, small monument, memorial, belltower, memorial monument, technical monument,  group of small monuments 
 ?item wdt:P31/wdt:P279* ?trida.                  #  small monument
  }

Try it!


Entertainment

Rock bands that start with "M"

SELECT DISTINCT ?band ?bandLabel
WHERE
{
  ?band  wdt:P31 wd:Q5741069 .
        ?band rdfs:label ?bandLabel .
  FILTER(STRSTARTS(?bandLabel, 'M')) .
}

Try it!


Films of directors by their English Wikipedia name

SELECT ?film ?filmLabel ?genere ?d WHERE {
  {
    SELECT ?film (GROUP_CONCAT(DISTINCT ?gL; SEPARATOR = ", ") AS ?genere) (MIN(YEAR(?date)) AS ?d) WHERE {
      ?sitelink schema:about ?director;
        schema:isPartOf <https://en.wikipedia.org/>;
        schema:name "Steven Spielberg"@en. # Edit this with different director's name to see their films. Use the English Wikipedia title only.
      ?film wdt:P31 wd:Q11424;
        wdt:P136 ?g, ?g.
      ?g rdfs:label ?gL.
      ?film wdt:P57 ?director;
        wdt:P577 ?date.
      FILTER((LANG(?gL)) = "en")
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    GROUP BY ?film
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC (?d)

Try it!

Winner of the Academy Awards by Award and Time

SELECT DISTINCT ?item ?itemLabel ?awardLabel ?time
{
    ?item wdt:P106/wdt:P279* wd:Q3455803 ; # Items with the Occupation(P106) of Director(Q3455803) or a subclass(P279)
          p:P166 ?awardStat .              # ... with an awarded(P166) statement
    ?awardStat pq:P805 ?award ;            # Get the award (which is "subject of" XXth Academy Awards)
               ps:P166 wd:Q103360 .        # ... that has the value Academy Award for Best Director(Q103360)
    ?award wdt:P585 ?time .                # the "point of time" of the Academy Award
    SERVICE wikibase:label {               # ... include the labels
        bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en"
    }
}
ORDER BY DESC(?time)

Try it!

Academy award data

SELECT ?human ?humanLabel ?awardEditionLabel ?awardLabel ?awardWork ?awardWorkLabel ?director ?directorLabel ?time
WHERE
{
  {
    SELECT (SAMPLE(?human) AS ?human) ?award ?awardWork (SAMPLE(?director) AS ?director) (SAMPLE(?awardEdition) AS ?awardEdition) (SAMPLE(?time) AS ?time) WHERE {
      ?award wdt:P31 wd:Q19020 .      # All items that are instance of(P31) of Academy awards (Q19020)
      {
        ?human p:P166 ?awardStat .              # Humans with an awarded(P166) statement
        ?awardStat ps:P166 ?award .        # ... that has any of the values of ?award
        ?awardStat pq:P805 ?awardEdition . # Get the award edition (which is "subject of" XXth Academy Awards)
        ?awardStat pq:P1686 ?awardWork . # The work they have been awarded for
        ?human wdt:P31 wd:Q5 .        # Humans
      } UNION {
        ?awardWork wdt:P31 wd:Q11424 . # Films
        ?awardWork p:P166 ?awardStat . # ... with an awarded(P166) statement
        ?awardStat ps:P166 ?award .        # ... that has any of the values of ?award
        ?awardStat pq:P805 ?awardEdition . # Get the award edition (which is "subject of" XXth Academy Awards)
      }
      OPTIONAL {
        ?awardEdition wdt:P585 ?time . # the "point of time" of the Academy Award
        ?awardWork wdt:P57 ?director .
      }
    }
    GROUP BY ?awardWork ?award # We only want every movie once for a category (a 'random' person is selected)
  }

  SERVICE wikibase:label {            # ... include the labels
    bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" .
  }
}
ORDER BY DESC(?time)

Try it!

People that received both Academy Award and Nobel Prize

The following query uses these:

  • Properties: award received (P166)  View with Reasonator View with SQID, instance of (P31)  View with Reasonator View with SQID
    SELECT DISTINCT ?person ?personLabel WHERE {
      ?person wdt:P166/wdt:P31? wd:Q7191 .
      ?person wdt:P166/wdt:P31? wd:Q19020 .
      SERVICE wikibase:label {
        bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" .
      }
    }
    

Number of handed out academy awards per award type

SELECT ?awardCount ?award ?awardLabel WHERE {
  {
    SELECT (COUNT(?award) AS ?awardCount) ?award
    WHERE
    {
      {
        SELECT (SAMPLE(?human) AS ?human) ?award ?awardWork (SAMPLE(?director) AS ?director) (SAMPLE(?awardEdition) AS ?awardEdition) (SAMPLE(?time) AS ?time) WHERE {
          ?award wdt:P31 wd:Q19020 .      # All items that are instance of(P31) of Academy awards (Q19020)
          {
            ?human p:P166 ?awardStat .              # Humans with an awarded(P166) statement
            ?awardStat ps:P166 ?award .        # ... that has any of the values of ?award
            ?awardStat pq:P805 ?awardEdition . # Get the award edition (which is "subject of" XXth Academy Awards)
            ?awardStat pq:P1686 ?awardWork . # The work they have been awarded for
            ?human wdt:P31 wd:Q5 .        # Humans
          } UNION {
            ?awardWork wdt:P31 wd:Q11424 . # Films
            ?awardWork p:P166 ?awardStat . # ... with an awarded(P166) statement
            ?awardStat ps:P166 ?award .        # ... that has any of the values of ?award
            ?awardStat pq:P805 ?awardEdition . # Get the award edition (which is "subject of" XXth Academy Awards)
          }
          OPTIONAL {
            ?awardEdition wdt:P585 ?time . # the "point of time" of the Academy Award
            ?awardWork wdt:P57 ?director .
          }
        }
        GROUP BY ?awardWork ?award # We only want every movie once for a category (a 'random' person is selected)
      }
    } GROUP BY ?award
    ORDER BY ASC(?awardCount)
  }
  SERVICE wikibase:label {            # ... include the labels
    bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" .
  }
}

Try it!

Film directors ranked by number of sitelinks multiplied by their number of films

SELECT ?director ?director_label ?films ?sitelinks ((?films * ?sitelinks) as ?rank)
WHERE {
  {SELECT ?director (count(distinct ?film) as ?films) (count(distinct ?sitelink) as ?sitelinks)
     WHERE { 
       ?director wdt:P106 wd:Q2526255 .         # has "film director" as occupation
     ?film wdt:P57 ?director .            # get all films directed by the director
       ?sitelink schema:about ?director .       # get all the sitelinks about the director
       } GROUP BY ?director }
SERVICE wikibase:label { 
  bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".  # Get label if it exists
?director rdfs:label ?director_label }  
} ORDER BY DESC(?rank)
LIMIT 100

Try it!

The Simpsons television series episodes list by season

SELECT ?show ?showLabel ?seasonNumber ?episode ?episodeLabel
WHERE {
  BIND(wd:Q886 as ?show) .
  ?season wdt:P361 ?show .
  ?episode wdt:P361 ?season .
  ?season p:P179 [
          pq:P1545 ?seasonNumber] .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
} ORDER BY xsd:integer(?seasonNumber)

Try it!

Pokémon!

# Updated 2020-06-17

# Gotta catch 'em all
SELECT DISTINCT ?pokemon ?pokemonLabel ?pokedexNumber
WHERE
{
    ?pokemon wdt:P31/wdt:P279* wd:Q3966183 .
    ?pokemon p:P1685 ?statement.
    ?statement ps:P1685 ?pokedexNumber;
              pq:P972 wd:Q20005020.
    FILTER (! wikibase:isSomeValue(?pokedexNumber) )
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
ORDER BY (?pokedexNumber)

Try it!

Law & Order episodes

# All Law & Order episodes on Wikidata.
# According to enwp, “[a] total of 456 original episodes… aired before cancellation” (https://en.wikipedia.org/wiki/List_of_Law_%26_Order_episodes).
# As of this writing, the query returns 451 results, so some episodes are missing (either without item or lacking the necessary statements to match this query).

SELECT (SAMPLE(?seasonNumber) AS ?seasonNumber) (SAMPLE(?episodeNumber) AS ?episodeNumber) (SAMPLE(?title) AS ?title) (MIN(?pubDate) AS ?pubDate) ?episode
{
  # All episodes should be instance of episode with series Law & Order.
  ?episode wdt:P31 wd:Q21191270;
           wdt:P179 wd:Q321423.
  # Many of them also have the season as series, so we can get episode and season number from qualifiers there.
  OPTIONAL {
    ?episode p:P179 [
      # the season also has series Law & Order
      ps:P179/p:P179 [
        ps:P179 wd:Q321423;
                pq:P1545 ?seasonNumber
      ] ;
      pq:P1545 ?episodeNumber
    ]
  }
  OPTIONAL { ?episode wdt:P1476 ?title. }
  OPTIONAL { ?episode wdt:P577 ?pubDate. }
}
GROUP BY ?episode # make sure we return each episode only once – a few have multiple publication dates, for example
ORDER BY IF(BOUND(?seasonNumber), xsd:integer(?seasonNumber), 1000) xsd:integer(?episodeNumber) ?title

Try it!

Main subjects of West Wing episodes

SELECT DISTINCT ?episode ?ordinal ?episodeLabel ?subject ?subjectLabel
WHERE {
  ?episode wdt:P31/wdt:P279* wd:Q1983062;
           p:P179 ?statement.
  OPTIONAL{ ?episode wdt:P921 ?subject }
  ?statement ps:P179 wd:Q3577037;
             pq:P1545 ?ordinal
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} ORDER BY xsd:integer(?ordinal)

Try it!

Movies with Bud Spencer

SELECT ?item ?itemLabel (MIN(?date) AS ?firstReleased) ?_image
WHERE {
  ?item wdt:P161 wd:Q221074;
        wdt:P577 ?date
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  OPTIONAL { ?item wdt:P18 ?_image. }
} GROUP BY ?item ?itemLabel ?_image
ORDER BY (?date)

Try it!

Fictional subjects of the Marvel Universe

SELECT ?char ?charName (GROUP_CONCAT(DISTINCT ?typeLabel;separator=", ") AS ?types) (GROUP_CONCAT(DISTINCT ?universeLabel;separator=", ") AS ?universes)
WHERE {
  ?char wdt:P1080 wd:Q931597;
          wdt:P31 ?type ;
          wdt:P1080 ?universe .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
                         ?char rdfs:label ?charName .
                         ?universe rdfs:label ?universeLabel .
                         ?type rdfs:label ?typeLabel .}
} GROUP BY ?char ?charName

Try it!

Contemporary Indian actresses

SELECT ?item ?itemLabel ?itemDescription (SAMPLE(?img) AS ?image) (SAMPLE(?dob) AS ?dob) ?sl
WHERE {
  ?item wdt:P106 wd:Q33999 ;
          wdt:P27 wd:Q668 ;
          wdt:P21 wd:Q6581072 .
  MINUS { ?item wdt:P570 [] }
  OPTIONAL { ?item wdt:P18 ?img }
  OPTIONAL { ?item wdt:P569 ?dob } 
  OPTIONAL { ?item wikibase:sitelinks ?sl } 
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en"}
} GROUP BY ?item ?itemLabel ?itemDescription ?sl
ORDER BY DESC(?sl)

Try it!

Articles on Punjabi (Gurmukhi) Wikipedia about Pakistani actresses

#added 2017-03-25 (46 results)
SELECT ?sitelink
WHERE
{
  # gender = female
    ?item wdt:P21 wd:Q6581072 .

    # country = Pakistan (Q25)
    { ?item wdt:P27 wd:Q843 }

        # occupation = actress (Q33999)
    { ?item wdt:P106 wd:Q33999 }
 
  # look for articles (sitelinks) in Punjabi ("pa")
    { ?sitelink schema:about ?item . ?sitelink schema:inLanguage "pa" }

  # humans only
    ?item wdt:P31 wd:Q5 .
}
#Listeria can only handle up to 5000
LIMIT 5000

Try it!

All Dr. Who performers

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, series ordinal (P1545)  View with Reasonator View with SQID, performer (P175)  View with Reasonator View with SQID
    #added 2017-07-16, updated 2020-07-08
    SELECT ?doctor ?doctorLabel ?ordinal ?performer ?performerLabel
    WHERE {
      ?doctor wdt:P31 wd:Q47543030 .
      OPTIONAL { ?doctor wdt:P1545 ?ordinal }
      OPTIONAL { ?doctor p:P175 / ps:P175 ?performer }
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
    }
    ORDER BY ASC(xsd:integer(?ordinal) )
    

Movies and their narrative location on a map

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#defaultView:Map
SELECT ?movie ?movieLabel ?narrative_location ?narrative_locationLabel ?coordinates WHERE {
   ?movie wdt:P840 ?narrative_location ;
          wdt:P31 wd:Q11424 .
   ?narrative_location wdt:P625 ?coordinates .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Movies released in 2017

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, publication date (P577)  View with Reasonator View with SQID
    SELECT DISTINCT ?item ?itemLabel WHERE {
      ?item wdt:P31 wd:Q11424.
      ?item wdt:P577 ?pubdate.
      FILTER((?pubdate >= "2017-01-01T00:00:00Z"^^xsd:dateTime) && (?pubdate <= "2017-12-31T00:00:00Z"^^xsd:dateTime))
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    }
    

Musicians or singers that have a genre containing 'rock'

SELECT DISTINCT ?human ?humanLabel
WHERE
{
    VALUES ?professions {wd:Q177220 wd:Q639669}
    ?human wdt:P31 wd:Q5 .
    ?human wdt:P106 ?professions .
    ?human wdt:P136 ?genre .
    ?human wikibase:statements ?statementcount .
    ?genre rdfs:label ?genreLabel .  
    FILTER CONTAINS(?genreLabel, "rock") .
    FILTER (?statementcount > 50 ) .
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
ORDER BY ?humanLabel
LIMIT 50

Try it!

Fictional characters whose birth/death date is in the current decade

The following query uses these:

  • Properties: subclass of (P279)  View with Reasonator View with SQID, instance of (P31)  View with Reasonator View with SQID, date of birth (P569)  View with Reasonator View with SQID, date of death (P570)  View with Reasonator View with SQID
    SELECT DISTINCT ?character ?characterLabel ?birth ?death WITH {
      # Fictional character subclasses as a named subquery
      SELECT ?fictiontype WHERE {
        ?fictiontype wdt:P279* wd:Q95074. hint:Prior hint:gearing "forward".
      }
    } AS %i
    WHERE
    {
      INCLUDE %i
      ?character wdt:P31 ?fictiontype.
      # Date of birth
      { ?character wdt:P569 ?birth . }
      # Date of death
      UNION { ?character wdt:P570 ?death . }
      # Get actual decade to compare with dates
      BIND(xsd:integer(YEAR(NOW())/10) as ?actual_decade).
      # Only show characters born or deceased in the current decade
      FILTER(xsd:integer(YEAR(?birth)/10) = ?actual_decade || xsd:integer(YEAR(?death)/10) = ?actual_decade)
      SERVICE wikibase:label {
        bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" . 
      }
    } ORDER BY ?birth ?death
    

Geography

Continents

Continents

SELECT ?continent ?continentLabel
WHERE
{
  ?continent wdt:P31 wd:Q5107.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY xsd:integer(SUBSTR(STR(?continent),STRLEN("http://www.wikidata.org/entity/Q")+1))

Try it!

Some other continents

continent (P30)

SELECT ?continentLabel
WHERE
{
  { # subquery for optimization so the label service doesn’t have to do as much work (228?ms vs 20731?ms)
    SELECT DISTINCT ?continent
    WHERE
    {
      [] wdt:P30 ?continent.
    }
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY xsd:integer(SUBSTR(STR(?continent),STRLEN("http://www.wikidata.org/entity/Q")+1))

Try it!

Places with continent Antarctica more than 3000?km north of south pole

#defaultView:Map
SELECT ?place ?placeLabel ?location WHERE {
  wd:Q933 wdt:P625 ?southPole.                         # coordinates of south pole
  ?place wdt:P30 wd:Q51;                               # continent: antarctica
         wdt:P625 ?location.
  FILTER(geof:distance(?location, ?southPole) > 3000). # over 3000?km away from south pole
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Try it!

Countries

List of present-day countries and capital(s)

SELECT DISTINCT ?country ?countryLabel ?capital ?capitalLabel
WHERE
{
  ?country wdt:P31 wd:Q3624078 .
  #not a former country
  FILTER NOT EXISTS {?country wdt:P31 wd:Q3024240}
  #and no an ancient civilisation (needed to exclude ancient Egypt)
  FILTER NOT EXISTS {?country wdt:P31 wd:Q28171280}
  OPTIONAL { ?country wdt:P36 ?capital } .

  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
ORDER BY ?countryLabel

Try it!

UN member states

SELECT DISTINCT ?state WHERE {
  ?state wdt:P31/wdt:P279* wd:Q3624078;
         p:P463 ?memberOfStatement.
  ?memberOfStatement a wikibase:BestRank;
                     ps:P463 wd:Q1065.
  MINUS { ?memberOfStatement pq:P582 ?endTime. }
  MINUS { ?state wdt:P576|wdt:P582 ?end. }
}

Try it!

Largest cities per country

#Largest cities per country
SELECT DISTINCT ?city ?cityLabel ?population ?country ?countryLabel ?loc WHERE {
  {
    SELECT (MAX(?population) AS ?population) ?country WHERE {
      ?city wdt:P31/wdt:P279* wd:Q515 .
      ?city wdt:P1082 ?population .
      ?city wdt:P17 ?country .
    }
    GROUP BY ?country
    ORDER BY DESC(?population)
  }
  ?city wdt:P31/wdt:P279* wd:Q515 .
  ?city wdt:P1082 ?population .
  ?city wdt:P17 ?country .
  ?city wdt:P625 ?loc .
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}

Try it!

Wikidata people per million inhabitants for all EU countries

#Interesting maintenance query that shows the relative prominence of a country's current (living) population on Wikidata. The query tends to time out when using all countries at once, but it might be possible to get the figures for each individual country by using uncommenting the line as indicated below
SELECT
  ?country ?countryLabel
  ?wikiPersons
  ?population
  (ROUND(?wikiPersons/?population*1000000) AS ?wikiPersonsPerM)
WHERE
{
  { SELECT ?country (count(*) as ?wikiPersons) WHERE {
    {SELECT DISTINCT ?person ?country WHERE {
      wd:Q458 wdt:P150 ?country .   # European Union  contains administrative territorial entity
      # BIND( wd:Q30 AS ?country ) # use instead of previous line to check individual countries
      ?person wdt:P31 wd:Q5 .
      ?person wdt:P27 ?country .
      FILTER NOT EXISTS{ ?person wdt:P570 ?date } # only count living people
    } }
  } GROUP BY ?country  }
  ?country wdt:P1082 ?population
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
ORDER BY DESC(?wikiPersonsPerM)

Try it!

Papers about wikidata

#papers about Wikidata
SELECT ?item ?itemLabel
WHERE
{
  ?item (wdt:P31/wdt:P279*) wd:Q191067.
  ?item wdt:P921 wd:Q2013.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
LIMIT 100

Try it!

Countries sorted by population

# defaultView:BubbleChart
SELECT DISTINCT ?countryLabel ?population
{
  ?country wdt:P31 wd:Q6256 ;
           wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
GROUP BY ?population ?countryLabel
ORDER BY DESC(?population)

Try it!

Country populations together with total city populations

Lists for each country the population and the total of the populations of all cities of this country. If data were complete and populations were measured at the same time for each country and the respective cities then the ratio would be 1.

SELECT ?country ?countryLabel ?population ?totalCityPopulation (?population / ?totalCityPopulation AS ?ratio) {
  ?country wdt:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
  {
    SELECT ?country (SUM(?cityPopulation) AS ?totalCityPopulation) WHERE {
      ?city wdt:P31 wd:Q515 .
      ?city wdt:P17 ?country .
      ?city wdt:P1082 ?cityPopulation .
    } GROUP BY ?country
  }
} ORDER BY ?ratio

Try it!

Names of African countries in all their official languages and English

The following query uses these:

  • Properties: continent (P30)  View with Reasonator View with SQID, official language (P37)  View with Reasonator View with SQID, instance of (P31)  View with Reasonator View with SQID, Wikimedia language code (P424)  View with Reasonator View with SQID
    SELECT DISTINCT ?item ?itemLabel_ol ?official_language ?itemLabel_en WHERE {
      ?item wdt:P30 wd:Q15 ;
            wdt:P37 ?officiallanguage ;
            wdt:P31 wd:Q6256 .
      ?officiallanguage wdt:P424 ?langcode .
      ?item rdfs:label ?itemLabel_ol . FILTER(lang(?itemLabel_ol)=?langcode)
      ?item rdfs:label ?itemLabel_en . FILTER(lang(?itemLabel_en)='en')
      ?officiallanguage rdfs:label ?official_language . FILTER(lang(?official_language)='en')
    }
    ORDER BY ?item ?itemLabel_lol ?official_language
    

Languages and dialects spoken in the Netherlands with their optional Wikipedia editions

select distinct ?language ?languageLabel ?wikipediaLabel where {
  ?language wdt:P31 ?instance;
            wdt:P17 wd:Q55.
  filter (?instance in (wd:Q34770, wd:Q33384)).
  optional { 
    ?wikipedia wdt:P31 wd:Q10876391;
               wdt:P407 ?language. 
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "nl,en". }
} group by ?language ?languageLabel ?wikipediaLabel

Try it!

Cities

Population of cities and towns in Denmark and their OSM relation id

# Population of cities and towns in Denmark and their OSM relation id
# This shows a simple OR using VALUES and a variable
SELECT ?city ?cityLabel ?population ?OSM_relation_ID WHERE {
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  VALUES ?town_or_city {
    wd:Q3957
    wd:Q515
  }
  ?city (wdt:P31/(wdt:P279*)) ?town_or_city;
    wdt:P17 wd:Q35.
  OPTIONAL { ?city wdt:P1082 ?population. }
  OPTIONAL { ?city wdt:P402 ?OSM_relation_ID. }
}
LIMIT 100

Try it!

Former capitals

#defaultView:Map
SELECT DISTINCT ?country ?countryLabel ?capital ?capitalLabel ?coordinates ?ended
WHERE
{
  ?country p:P36 ?stat.
  ?stat ps:P36 ?capital.
  ?capital wdt:P625 ?coordinates.
  OPTIONAL {
    ?country wdt:P582|wdt:P576 ?ended.
  }
  OPTIONAL {
    ?capital wdt:P582|wdt:P576 ?ended.
  }
  OPTIONAL {
    ?stat pq:P582 ?ended.
  }
  FILTER(BOUND(?ended)).
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Try it!

Largest cities of the world

#defaultView:BubbleChart
SELECT DISTINCT ?cityLabel ?population ?gps
WHERE
{
  ?city wdt:P31/wdt:P279* wd:Q515 .
  ?city wdt:P1082 ?population .
  ?city wdt:P625 ?gps .
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}
ORDER BY DESC(?population) LIMIT 100

Try it!

Cities as big as Eindhoven give or take 1000

#defaultView:Map
SELECT DISTINCT ?city ?cityLabel ?location ?populatie2 WHERE {
  wd:Q9832 wdt:P1082 ?populatie .
  ?city wdt:P1082 ?populatie2 ;
        wdt:P625 ?location .
  FILTER (abs(?populatie - ?populatie2) < 1000)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],nl" }
}

Try it!

Where in the world is Antwerp

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#defaultView:Map
SELECT DISTINCT ?settlement ?name ?coor
WHERE
{
  
   ?subclass_settlement wdt:P279+ wd:Q486972 .
   ?settlement wdt:P31 ?subclass_settlement ;
               wdt:P625 ?coor ;
                rdfs:label ?name .
   FILTER regex(?name, "Antwerp", "i")

}

Destinations from Antwerp International airport

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#defaultView:Map
SELECT ?connectsairport ?connectsairportLabel ?place_served ?place_servedLabel ?coor
WHERE
{
  VALUES ?airport { wd:Q17480 } # Antwerp international airport  wd:Q17480
  ?airport wdt:P81 ?connectsairport ;
           wdt:P625 ?base_airport_coor .
  ?connectsairport wdt:P931 ?place_served ;
                   wdt:P625 ?coor .
 
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Cities connected by the European route E40

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#defaultView:Map
SELECT ?city ?cityLabel ?coordinates
WHERE
{
   VALUES ?highway {wd:Q327162 }
   ?highway wdt:P2789 ?city .
    ?city wdt:P625 ?coordinates .
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Cities connected by the Trans-Mongolian and Trans-Siberian Railway

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#defaultView:Map
SELECT ?city ?cityLabel ?coordinates
WHERE
{
   VALUES ?highway { wd:Q559037 wd:Q58767 }
   ?highway wdt:P2789 ?city .
    ?city wdt:P625 ?coordinates .
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Cities connected to Paramaribo (Suriname) by main roads

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#defaultView:Map
SELECT DISTINCT ?connection ?connectionLabel ?connectedWith ?connectedWithLabel ?coor
WHERE
{
  VALUES ?city {wd:Q3001} # wd:Q3001 = Paramaribo}
  ?connection wdt:P2789+ ?city ;
              wdt:P2789+ ?connectedWith .
  ?connectedWith wdt:P625 ?coor .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
  }

Names of 100 cities with a population larger than 1000000 in the native languages of their countries

The following query uses these:

  • Properties: population (P1082)  View with Reasonator View with SQID, instance of (P31)  View with Reasonator View with SQID, country (P17)  View with Reasonator View with SQID, official language (P37)  View with Reasonator View with SQID, Wikimedia language code (P424)  View with Reasonator View with SQID
    # Show the names of 100 cities with a population larger than 1000000 in the native languages of their countries
    SELECT ?city ?cityLabel ?country ?countryLabel ?lang ?langLabel ?langCode ?population
    WHERE
    {
      ?city wdt:P1082 ?population .
     
      FILTER(?population>1000000)
     
      ?city wdt:P31 wd:Q515;
            wdt:P17 ?country;
            rdfs:label ?cityLabel .
      ?country wdt:P37 ?lang;
               rdfs:label ?countryLabel .
      ?lang wdt:P424 ?langCode;
            rdfs:label ?langLabel .
     
      FILTER(lang(?cityLabel)=?langCode)
      FILTER(lang(?countryLabel)=?langCode)
      FILTER(lang(?langLabel)=?langCode)
    } LIMIT 100
    

Distances between any two cities or municipalities in an area

grouped by dist range, color-coded

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, located in the administrative territorial entity (P131)  View with Reasonator View with SQID, coordinate location (P625)  View with Reasonator View with SQID
    #defaultView:BarChart
    PREFIX var_muntype: <http://www.wikidata.org/entity/Q15284>
    PREFIX var_area: <http://www.wikidata.org/entity/Q6308>
    SELECT ?from ?to ?distGrp WHERE {
      {
        SELECT ?from ?to ?distNum ?mun ?mun2 WHERE {
          { SELECT ?mun (SAMPLE(?loc) AS ?loc)
            WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                         wdt:P131 var_area:;
                         wdt:P625 ?loc. }
            GROUP BY ?mun
          }
          OPTIONAL {
            { SELECT (?mun AS ?mun2) (SAMPLE(?loc) AS ?loc2)
              WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                           wdt:P131 var_area:;
                           wdt:P625 ?loc. }
              GROUP BY ?mun
            }
          }
          BIND(geof:distance(?loc, ?loc2) AS ?distNum).
    
          SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
            ?mun rdfs:label ?from.
            ?mun2 rdfs:label ?to.
          }
        }
      }
      FILTER(CONCAT(?from,STR(?mun)) <= CONCAT(?to,STR(?mun2))).
      #BIND(IF(STR(?from) < STR(?to),CONCAT(?from," <--> ",?to),
      #  CONCAT(?to," <--> ",?from)) AS ?distLabel).
    
      BIND(COALESCE(
        IF(?distNum >= 40, "40 - .. km", 1/0),
        IF(?distNum >= 30, "30 - 40 km", 1/0),
        IF(?distNum >= 20, "20 - 30 km", 1/0),
        IF(?distNum >= 10, "10 - 20 km", 1/0),
        IF(?distNum >= 5, "05 - 10 km", 1/0),
        IF(?distNum >= 1, "01 - 05 km", "00 - 01 km")) AS ?distGrp).
    }
    ORDER BY ?from ?distGrp
    
grouped per municipality on x-axis, alphabetically

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, located in the administrative territorial entity (P131)  View with Reasonator View with SQID, coordinate location (P625)  View with Reasonator View with SQID
    #defaultView:ScatterChart
    PREFIX var_muntype: <http://www.wikidata.org/entity/Q15284>
    PREFIX var_area: <http://www.wikidata.org/entity/Q6308>
    SELECT ?from (?distGrp1 AS ?kilometers) ?to WHERE {
      { SELECT ?mun (SAMPLE(?loc) AS ?loc)
        WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                     wdt:P131 var_area:;
                     wdt:P625 ?loc. }
        GROUP BY ?mun
      }
      OPTIONAL {
        { SELECT (?mun AS ?mun2) (SAMPLE(?loc) AS ?loc2)
          WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                       wdt:P131 var_area:;
                       wdt:P625 ?loc. }
          GROUP BY ?mun
        }
      }
      BIND(geof:distance(?loc, ?loc2) AS ?distNum).
      BIND(STR(ROUND(?distNum)) AS ?distGrp0).
      BIND(CONCAT(SUBSTR("000",STRLEN(?distGrp0)+1),?distGrp0,".",STR(ROUND((?distNum-FLOOR(?distNum))*10))," km") AS ?distGrp1).
    
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
        ?mun rdfs:label ?from.
        ?mun2 rdfs:label ?to.
      }
    }
    ORDER BY ?from ?kilometers
    
grouped per municipality on x-axis, by sum of dist

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, located in the administrative territorial entity (P131)  View with Reasonator View with SQID, coordinate location (P625)  View with Reasonator View with SQID
    #defaultView:ScatterChart
    PREFIX var_muntype: <http://www.wikidata.org/entity/Q15284>
    PREFIX var_area: <http://www.wikidata.org/entity/Q6308>
    SELECT ?from (?distNum AS ?kilometers) ?to WHERE {
      { SELECT ?mun (SAMPLE(?loc) AS ?loc)
        WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                     wdt:P131 var_area:;
                     wdt:P625 ?loc. }
        GROUP BY ?mun
      }
      OPTIONAL {
        { SELECT (?mun AS ?mun2) (SAMPLE(?loc) AS ?loc2)
          WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                       wdt:P131 var_area:;
                       wdt:P625 ?loc. }
          GROUP BY ?mun
        }
      }
      BIND(geof:distance(?loc, ?loc2) AS ?distNum).
    
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
        ?mun rdfs:label ?from.
        ?mun2 rdfs:label ?to.
      }
    }
    ORDER BY ?from ?kilometers
    
grouped per municipality on x-axis, animated per municipality on x-axis

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, located in the administrative territorial entity (P131)  View with Reasonator View with SQID, coordinate location (P625)  View with Reasonator View with SQID
    #defaultView:ScatterChart
    PREFIX var_muntype: <http://www.wikidata.org/entity/Q15284>
    PREFIX var_area: <http://www.wikidata.org/entity/Q6308>
    SELECT ?from (?distNum AS ?kilometers) ?to (?from AS ?animation) WHERE {
      { SELECT ?mun (SAMPLE(?loc) AS ?loc)
        WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                     wdt:P131 var_area:;
                     wdt:P625 ?loc. }
        GROUP BY ?mun
      }
      OPTIONAL {
        { SELECT (?mun AS ?mun2) (SAMPLE(?loc) AS ?loc2)
          WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                       wdt:P131 var_area:;
                       wdt:P625 ?loc. }
          GROUP BY ?mun
        }
      }
      BIND(geof:distance(?loc, ?loc2) AS ?distNum).
    
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
        ?mun rdfs:label ?from.
        ?mun2 rdfs:label ?to.
      }
    }
    ORDER BY ?from ?kilometers
    
grouped per municipality on x-axis, animated per municipality on z-axis

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, located in the administrative territorial entity (P131)  View with Reasonator View with SQID, coordinate location (P625)  View with Reasonator View with SQID
    #defaultView:ScatterChart
    PREFIX var_muntype: <http://www.wikidata.org/entity/Q15284>
    PREFIX var_area: <http://www.wikidata.org/entity/Q6308>
    SELECT ?from (?distNum AS ?kilometers) ?to (?to AS ?animation) WHERE {
      { SELECT ?mun (SAMPLE(?loc) AS ?loc)
        WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                     wdt:P131 var_area:;
                     wdt:P625 ?loc. }
        GROUP BY ?mun
      }
      OPTIONAL {
        { SELECT (?mun AS ?mun2) (SAMPLE(?loc) AS ?loc2)
          WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                       wdt:P131 var_area:;
                       wdt:P625 ?loc. }
          GROUP BY ?mun
        }
      }
      BIND(geof:distance(?loc, ?loc2) AS ?distNum).
    
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
        ?mun rdfs:label ?from.
        ?mun2 rdfs:label ?to.
      }
    }
    ORDER BY ?from ?kilometers
    
grouped per municipality on x-axis, animated by fixed dist range groups

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, located in the administrative territorial entity (P131)  View with Reasonator View with SQID, coordinate location (P625)  View with Reasonator View with SQID
    #defaultView:ScatterChart
    PREFIX var_muntype: <http://www.wikidata.org/entity/Q15284>
    PREFIX var_area: <http://www.wikidata.org/entity/Q6308>
    SELECT ?from (?distNum AS ?kilometers) ?to (?distGrp AS ?animation) WHERE {
      { SELECT ?mun (SAMPLE(?loc) AS ?loc)
        WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                     wdt:P131 var_area:;
                     wdt:P625 ?loc. }
        GROUP BY ?mun
      }
      OPTIONAL {
        { SELECT (?mun AS ?mun2) (SAMPLE(?loc) AS ?loc2)
          WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                       wdt:P131 var_area:;
                       wdt:P625 ?loc. }
          GROUP BY ?mun
        }
      }
      #FILTER (STR(?mun) <= STR(?mun2)).
      BIND(geof:distance(?loc, ?loc2) AS ?distNum).
      BIND(COALESCE(
        IF(?distNum >= 40, "40 km und mehr", 1/0),
        IF(?distNum >= 30, "30 - 40 km", 1/0),
        IF(?distNum >= 20, "20 - 30 km", 1/0),
        IF(?distNum >= 10, "10 - 20 km", 1/0),
        IF(?distNum >= 5, "05 - 10 km", 1/0),
        IF(?distNum >= 1, "01 - 05 km", "00 - 01 km")) AS ?distGrp).
      
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
        ?mun rdfs:label ?from.
        ?mun2 rdfs:label ?to.
      }
    }
    ORDER BY ?animation ?from ?kilometers
    
grouped per municipality on x-axis, animated by ranked dist (farthest, 2nd farthest, ..)

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, located in the administrative territorial entity (P131)  View with Reasonator View with SQID, coordinate location (P625)  View with Reasonator View with SQID
    #defaultView:ScatterChart
    PREFIX var_muntype: <http://www.wikidata.org/entity/Q15284>
    PREFIX var_area: <http://www.wikidata.org/entity/Q6308>
    SELECT ?from ?kilometers ?to ?rank_group
    WHERE {
      {
        SELECT (SAMPLE(?mun) AS ?mun) (SAMPLE(?mun2) AS ?mun2) (SAMPLE(?distNum) AS ?kilometers)
               (COUNT(*)-1 AS ?rg) (SUBSTR("00",1+STRLEN(STR(?rg))) AS ?rgpad)
               (IF(FLOOR((?rg-(100*FLOOR(?rg/100)))/10)=1,0,?rg-(10*FLOOR(?rg/10))) AS ?rgmod)
               (IF(?rgmod=1,"st",IF(?rgmod=2,"nd",IF(?rgmod=3,"rd","th"))) AS ?rgord)
               (CONCAT(?rgpad,STR(?rg),?rgord,"-most farthest places") AS ?rank_group)
        WHERE {
          { SELECT ?mun (SAMPLE(?loc) AS ?loc)
            WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                         wdt:P131 var_area:;
                         wdt:P625 ?loc. }
            GROUP BY ?mun
          }
          OPTIONAL {
            { SELECT (?mun AS ?mun2) (SAMPLE(?loc) AS ?loc2)
              WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                           wdt:P131 var_area:;
                           wdt:P625 ?loc. }
              GROUP BY ?mun
            }
          }
          OPTIONAL {
            { SELECT (?mun AS ?mun3) (SAMPLE(?loc) AS ?loc3)
              WHERE { ?mun wdt:P31/wdt:P279* var_muntype:;
                           wdt:P131 var_area:;
                           wdt:P625 ?loc. }
              GROUP BY ?mun
            }
          }
          BIND(geof:distance(?loc, ?loc2) AS ?distNum).
          BIND(geof:distance(?loc, ?loc3) AS ?d).
          FILTER(?distNum >= ?d).
        } GROUP BY ?mun ?mun2 ?distNum
      }
      
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en".
        ?mun rdfs:label ?from.
        ?mun2 rdfs:label ?to.
      }
    }
    ORDER BY ?rank_group ?kilometers ?from
    

Show all Dutch municipalities that share a border with Alphen aan den Rijn (Q213246), ignoring rank

select ?muni ?muniLabel where {
  ?muni p:P31 [ps:P31 wd:Q2039348];
        wdt:P47 wd:Q213246.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "nl". }
}

Try it!

Border cities of the world

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

# To filter by country add FILTER (?country = wd:Qxx)
#defaultView:Map
# To show the cities of several countries use FILTER (?country IN (wd:Qxx, wd:Qyy))
# To obtain cities that are part of a particular continent or territory ?country
# should not be optional and add "?country wdt:P361 wd:Qxx ."

SELECT ?border_city ?border_cityLabel ?countryLabel ?coords 
WHERE {
  ?border_city wdt:P31 wd:Q902814.
  OPTIONAL { ?border_city wdt:P17 ?country. }
  OPTIONAL { ?border_city wdt:P625 ?coords. }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". 
                         ?border_city rdfs:label ?border_cityLabel.
                         ?country  rdfs:label ?countryLabel.}
}
GROUP BY ?border_city ?border_cityLabel ?countryLabel ?coords
order by ?countryLabel ?border_cityLabel

Rivers

Longest rivers

The following query uses these:

Features: BubbleChart (Q24515280)  View with Reasonator View with SQID

#defaultView:BubbleChart
SELECT ?item ?itemLabel ?length ?pic ?location
WHERE
{
  ?item wdt:P31/wdt:P279* wd:Q4022 .
  ?item wdt:P2043 ?length .
  ?item wdt:P18 ?pic .
  ?item wdt:P625 ?location
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . }
} ORDER BY DESC(?length) ?itemLabel
LIMIT 50

Longest river of each continent

The following query uses these:

  • Properties: instance of (P31)  View with Reasonator View with SQID, subclass of (P279)  View with Reasonator View with SQID, length (P2043)  View with Reasonator View with SQID, continent (P30)  View with Reasonator View with SQID
    SELECT ?continent ?river ?continentLabel ?riverLabel
    WHERE
    {
      {
        SELECT ?continent (MAX(?length) AS ?length)
        WHERE
        {
          ?river wdt:P31/wdt:P279* wd:Q355304;
                 wdt:P2043 ?length;
                 wdt:P30 ?continent.
        }
        GROUP BY ?continent
      }
      ?river wdt:P31/wdt:P279* wd:Q355304;
             wdt:P2043 ?length;
             wdt:P30 ?continent.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    ORDER BY ?continentLabel
    

Rivers in Antarctica

SELECT ?river ?riverLabel ?location
WHERE
{
  ?river wdt:P31/wdt:P279* wd:Q355304; # watercourse; includes a few creeks – use wd:Q4022 for rivers only
         wdt:P30 wd:Q51.
  OPTIONAL { ?river wdt:P625 ?location. }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Try it!

Body of water with the most watercourses ending in it

# Bodies of water that most watercourses end in (transitive).
# For example, over 4000 watercourses eventually flow into the Ob,
# and since the Ob flows into the Kara Sea, the Kara Sea has over 4000 results as well.
SELECT ?mouth (COUNT(?watercourse) AS ?count)
WHERE
{
  ?watercourse wdt:P403+ ?mouth.
}
GROUP BY ?mouth
ORDER BY DESC(?count)
LIMIT 10

Try it!

Bridges over rivers in former government district of Leipzig

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#defaultView:Map
SELECT (SAMPLE(?bridge) AS ?bridge) (SAMPLE(?bridgeLabel) AS ?bridgeLabel)
       (SAMPLE(?watercourse) AS ?watercourse) (SAMPLE(?watercourseLabel) AS ?watercourseLabel)
       (SAMPLE(?loc) AS ?loc) (SAMPLE(?pic) AS ?pic)
       (CONCAT(SAMPLE(?sKey),": ",STR(YEAR(SAMPLE(?s)))) AS ?start)
       (CONCAT(SAMPLE(?eKey),": ",STR(YEAR(SAMPLE(?e)))) AS ?end)
       (SAMPLE(?article) AS ?article) (IF(BOUND(?article),CONCAT(?bridgeLabel," in Wikipedia"),1/0) AS ?articleLabel)
WHERE {
  {
    SELECT ?bridge ?watercourse WHERE {
      ?bridge wdt:P31/wdt:P279* wd:Q12280; wdt:P177 ?watercourse.
      ?watercourse wdt:P31/wdt:P279* wd:Q355304.
      # the following actually yields a perf penalty atm
      #?bridge wdt:P17 wd:Q183.
      #OPTIONAL { ?bridge wdt:P17 ?country. }. FILTER(!BOUND(?country) || ?country = wd:Q183).
    }
  }

  # wd:Q1202, wd:Q183 work as well atm and take progressively more time to complete
  ?bridge (p:P131|ps:P131)+ wd:Q24186.

  OPTIONAL { ?bridge wdt:P625 ?loc. }.
  OPTIONAL { ?bridge wdt:P18 ?pic. }.
  OPTIONAL { ?bridge wdt:P571 ?s. }.
  OPTIONAL { ?bridge wdt:P576 ?e. }.
  
  OPTIONAL {
    ?article schema:about ?bridge.
    FILTER (IF(EXISTS {?article schema:inLanguage "[AUTO_LANGUAGE]".},
               SUBSTR(str(?article), 1, 25) = "https://[AUTO_LANGUAGE].wikipedia.org/",
               IF(EXISTS {?article schema:inLanguage "en".},
                  SUBSTR(str(?article), 1, 25) = "https://en.wikipedia.org/",
                  SUBSTR(str(?article), 1, 25) = "https://de.wikipedia.org/"
               )
            )).
  }

  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en,de".
    ?bridge rdfs:label ?bridgeLabel.
    ?watercourse rdfs:label ?watercourseLabel.
    wd:P571 rdfs:label ?sKey.
    wd:P576 rdfs:label ?eKey.
  }
}
GROUP BY ?bridge ?watercourse

Mountains

Mountains, with coordinates, not located on Earth

SELECT DISTINCT ?item ?name ?coord ?lat ?lon ?globe
{
   ?item wdt:P31 wd:Q8502 ;
         p:P625 [
           psv:P625 [
             wikibase:geoLatitude ?lat ;
             wikibase:geoLongitude ?lon ;
             wikibase:geoGlobe ?globe ;
           ] ;
           ps:P625 ?coord
         ]
  FILTER ( ?globe != wd:Q2 )
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
    ?item rdfs:label ?name
   }
}
ORDER BY ASC (?name)

Try it!

Highest mountains in the universe

#Elevations over 8000 (meter, feet or other)
#Note the absence of units and the presence of coordinates
#Last updated 2021-04-25

SELECT ?elevation ?item ?itemLabel ?itemDescription ?coord
WHERE
{
  ?item wdt:P2044 ?elevation .
  filter(?elevation > 8000)
  ?item wdt:P625 ?coord .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY DESC(?elevation)

Try it!

Highest mountains in the universe (with units)

#Elevations over 8000 
#Displays units
#Last updated 2021-04-25

SELECT ?elevation ?unit ?unitLabel ?item ?itemLabel ?itemDescription ?coord
WHERE
{
  ?psv_triples wikibase:quantityAmount ?elevation .
  filter(?elevation > 8000) 
  ?psv_triples wikibase:quantityUnit ?unit .

  ?p_triples psv:P2044 ?psv_triples .  
  ?p_triples a wikibase:BestRank .
  
  ?item p:P2044 ?p_triples .
  
  ?item wdt:P625 ?coord .
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY DESC(?elevation)

Try it!


Highest mountains in the universe (with units, compact form)

#Elevations over 8000 
#Displays units
#Last updated 2021-04-25

SELECT ?elevation ?unit ?unitLabel ?item ?itemLabel ?itemDescription ?coord
WHERE
{
  ?item wdt:P2044 ?elevation . 
  # this could be dropped, but is included to speed it up
  filter(?elevation > 8000) 

  ?item p:P2044 [ a wikibase:BestRank ; psv:P2044 [ wikibase:quantityAmount ?elevation ; wikibase:quantityUnit ?unit ] ] .

  ?item wdt:P625 ?coord .
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY DESC(?elevation)

Try it!

Mountains over 8000 meters elevation

#Last updated 2021-04-25
#defaultView:Map
SELECT ?item ?itemLabel ?itemDescription ?coord ?elevation
WHERE
{
  ?item wdt:P31 wd:Q8502 .
  ?item p:P2044 [ a wikibase:BestRank; psn:P2044/wikibase:quantityAmount ?elevation ]
  FILTER(?elevation >= 8000 )
  ?item wdt:P625 ?coord.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}

Try it!

Italian mountains higher than 4000 meters

#defaultView:ImageGrid
SELECT ?item ?itemLabel ?coord ?elev ?picture
{
  ?item p:P2044/psn:P2044/wikibase:quantityAmount ?elev ;  # normalized height
        wdt:P625 ?coord ;
        wdt:P17 wd:Q38 ;
        wdt:P18 ?picture
  FILTER(?elev > 4000)

  SERVICE wikibase:label { bd:serviceParam wikibase:language "it" }
}

Try it!

Metro stations in Paris

SELECT ?item ?itemLabel ?adjacent ?adjacentL ?coords
{
  ?item wdt:P31/wdt:P279* wd:Q928830 ;
        wdt:P81 wd:Q13224 ;
        wdt:P625 ?coords .
  OPTIONAL {
    ?item p:P197 [ ps:P197 ?adjacent ; pq:P5051 wd:Q585752;
                                       pq:P81 wd:Q13224] .
    ?adjacent rdfs:label ?adjacentL filter (lang(?adjacentL) = "en")
  }
?item wdt:P1619 ?founded_date. #needs existence
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . }
} ORDER BY ?itemLabel

Try it!

Map of Broadway venues

#defaultView:Map
# Venues in Broadway
SELECT DISTINCT ?venue ?venueLabel ?coords {
    ?venue wdt:P1217 ?IDBDB .
    wd:Q235065 wdt:P625 ?broadWayLoc .

    SERVICE wikibase:around {
      ?venue wdt:P625 ?coords .
      bd:serviceParam wikibase:center ?broadWayLoc .
      bd:serviceParam wikibase:radius "1.5" .
    }

  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}

Try it!

How many states this US state borders

SELECT ?state ?stateLabel ?borders
WHERE
{
  {
    SELECT ?state (COUNT(?otherState) as ?borders)
    WHERE
    {
    ?state wdt:P31 wd:Q35657 .
    ?otherState wdt:P47 ?state .
    ?otherState wdt:P31 wd:Q35657 .
    }
    GROUP BY ?state
  }
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" .
  }
}        
ORDER BY DESC(?borders)

Try it!

Places that are below 10 meters above sea level

#defaultView:Map
SELECT ?place ?location ?elev ?image
WHERE
{
  ?place p:P2044/psv:P2044 ?placeElev.
  ?placeElev wikibase:quantityAmount ?elev.
  ?placeElev wikibase:quantityUnit ?unit.
  bind(0.01 as ?km).
  filter( (?elev < ?km*1000 && ?unit = wd:Q11573)
       || (?elev < ?km*3281 && ?unit = wd:Q3710)
       || (?elev < ?km      && ?unit = wd:Q828224) ).
  ?place wdt:P625 ?location.
  optional { ?place wdt:P18 ?image }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}

Try it!

Globes used to represent coordinates

SELECT (count(?v) as ?c) ?globe
WHERE
{
  ?v wikibase:geoGlobe ?globe
}
GROUP BY ?globe
ORDER BY DESC(?c)

Try it!

Places within 1km of the Empire State Building

SELECT ?place ?placeLabel ?location ?instanceLabel
WHERE
{
  wd:Q9188 wdt:P625 ?loc .
  SERVICE wikibase:around {
      ?place wdt:P625 ?location .
      bd:serviceParam wikibase:center ?loc .
      bd:serviceParam wikibase:radius "1" .
  }
  OPTIONAL {    ?place wdt:P31 ?instance  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
  BIND(geof:distance(?loc, ?location) as ?dist)
} ORDER BY ?dist

Try it!

Select French municipalities by INSEE code (select by identifier)

SELECT ?item ?itemLabel ?inseeCode {
  ?item wdt:P374 ?inseeCode .
  FILTER (?inseeCode in ("75056", "69123", "13055"))
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}

Try it!


Map and list of municipalities in The Netherlands

#Concise list & map of the 355 Dutch municipalities, their geo coordinates and their provinces, per 1-1-2019
#See also: 
#https://almanak.overheid.nl/organisaties/Gemeenten/ - 355 in aantal
#https://nl.wikipedia.org/wiki/Lijst_van_Nederlandse_gemeenten - 355 in aantal

#defaultView:Map
select ?muni ?muniLabel ?location where {
  ?muni p:P31 ?instanceOf; # Get statement because we need this later
        wdt:P625 ?location. # And location
  ?instanceOf ps:P31 wd:Q2039348. # P31 should be 'municipality of the Netherlands'
  minus { ?muni wdt:P31 wd:Q7265977. } # Don't show former municipalities
  minus { ?instanceOf pq:P582 ?endTime. } # And don't show municipalities that have an end time
  service wikibase:label { bd:serviceParam wikibase:language "nl". } # Show names in Dutch
}

Try it!


Emergency numbers by population using them

#Lists emergency numbers and the total amount of people which can use them
#defaultView:BubbleChart
SELECT ?emergencyNumber ?emergencyNumberLabel ?tel ?population ?countries
WHERE
{
 ?emergencyNumber wdt:P31 wd:Q694554 .
  OPTIONAL{SELECT ?emergencyNumber (COUNT(?state) as ?countries) (SUM(?pop) as ?population) WHERE {
    ?state wdt:P2852 ?emergencyNumber .
    OPTIONAL{?state wdt:P1082 ?pop} .
    ?state wdt:P31/wdt:P279* wd:Q6256
  } GROUP BY ?emergencyNumber } .
  OPTIONAL{?emergencyNumber wdt:P1329 ?tel }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
ORDER BY DESC(?population)

Try it!

German states, ordered by the number of company headquarters per million inhabitants

# German states, ordered by the number of company headquarters per million inhabitants
# Replace wd:Q1221156 (state of Germany) by anything else you care about, e.g., wd:Q6256 (country)
# Nested queries for correctness (don't count companies twice) and performance (aggregate before adding more data)
# Limits: states without population missing; company data in Wikidata is always incomplete
# Note: This query shows some not-so-easy nesting of DISTINCT (don't count any company twice) and aggregate, in combination with arithmetic output evaluation functions. It is a hard query that may time out if modified.
SELECT
  ?state ?stateLabel
  ?companies
  ?population
  (?companies/?population*1000000 AS ?companiesPerM)
WHERE
{
  { SELECT ?state (count(*) as ?companies) WHERE {
    {SELECT DISTINCT ?company ?state WHERE {
      ?state wdt:P31 wd:Q1221156 .
      ?company wdt:P31/wdt:P279* wd:Q4830453 .
      ?company wdt:P159/wdt:P131* ?state .
      FILTER NOT EXISTS{ ?company wdt:P576 ?date } # don't count dissolved companies
    } }
  } GROUP BY ?state  }
    ?state wdt:P1082 ?population
  SERVICE wikibase:label { bd:serviceParam wikibase:language "de" }
}
ORDER BY DESC(?companiesPerM)

Try it!

Popular names per birthplace

#defaultView:BubbleChart
SELECT ?cid ?firstname (COUNT(*) AS ?count)
WHERE
{
  ?pid wdt:P19 wd:Q64.
  ?pid wdt:P735 ?cid.
  OPTIONAL {
    ?cid rdfs:label ?firstname
    FILTER((LANG(?firstname)) = "en")
  }
}
GROUP BY ?cid ?firstname
ORDER BY DESC(?count) ?firstname
LIMIT 50

Try it!

Map of places mentioned in travel stories with text in French accessible online

#defaultView:Map
SELECT DISTINCT ?item ?itemLabel ?ed ?edLabel ?auteurLabel (year(?dateCreation) as ?AnneeCreation) ?lieuLabel ?coord ?lien
WHERE
{
  ?item wdt:P136 wd:Q1164267 .    # genre :récit de voyage
  ?item  wdt:P31 wd:Q571 .        # nature : livre
  OPTIONAL{
    ?item wdt:P50 ?auteur .       # [option] auteur
  }
  OPTIONAL{
    ?item wdt:P571 ?dateCreation. # [option] date de création              
  }
 
  ?item  wdt:P840 ?lieu .         # lieu de l'action
  MINUS {?item  wdt:P840 wd:Q933} # (bug du Pôle Sud)
  ?lieu wdt:P625 ?coord .         # coordonnées géographiques du lieu
 
  {
    ?item wdt:P953 ?lien .        # URL, texte intégral disponible sur
    ?item wdt:P407 wd:Q150        # langue de l'œuvre : français
  }UNION{
    ?ed wdt:P629 ?item .          # édition du livre
    ?ed wdt:P953 ?lien .          # URL, texte intégral disponible sur 
    ?ed wdt:P407 wd:Q150          # langue de l'œuvre : français
  }

  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],fr". }
} ORDER BY ?dateCreation

Try it!

Things located where the equator meets the prime meridian

SELECT ?place ?placeLabel ?location
WHERE
{
  wd:Q24041662 wdt:P625 ?loc00 .
  SERVICE wikibase:around {
    ?place wdt:P625 ?location .
    bd:serviceParam wikibase:center ?loc00 .
    bd:serviceParam wikibase:radius "0.001" .
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" .  }
}
ORDER BY ?placeLabel

Try it!

French communes with names ending in ac

#defaultView:Map
SELECT ?item ?itemLabel ?coord
WHERE
{
  ?item wdt:P31/wdt:P279* wd:Q484170;
        wdt:P17 wd:Q142;
        rdfs:label ?itemLabel;
        wdt:P625 ?coord;
  FILTER (lang(?itemLabel) = "fr").
  FILTER regex (?itemLabel, "ac$").
  FILTER not exists { ?item wdt:P131 wd:Q33788 } # excluding Koumac, New Caledonia...
}

Try it!

Buildings in more than one country

SELECT ?item ?itemLabel ?count
WHERE
{
  {
    SELECT ?item (COUNT(DISTINCT ?country) AS ?count) WHERE {
      ?item wdt:P31/wdt:P279* wd:Q41176 .
      ?item wdt:P17 ?country .
      FILTER NOT EXISTS { ?country wdt:P576 ?end }
    }
    GROUP BY ?item
  }
  FILTER ( ?count > 1 )
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . }
}
ORDER BY DESC(?count) ?itemL

Try it!

Streets named after a person

SELECT ?street ?streetLabel ?cityLabel ?personLabel
WHERE
{
    ?street wdt:P31 wd:Q79007 .
    ?street wdt:P17 wd:Q142 .
    ?street wdt:P131 ?city .
    ?street wdt:P138 ?person .
    ?person wdt:P31 wd:Q5
    SERVICE wikibase:label { bd:serviceParam wikibase:language "fr" }
}
ORDER BY ?city

Try it!

Streets in France without a city

SELECT ?street ?streetLabel
WHERE
{
    ?street wdt:P31/wdt:P279* wd:Q79007 .
    ?street wdt:P17 wd:Q142 .
    MINUS { ?street wdt:P131 [] } .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr" }
}
ORDER BY ?streetLabel

Try it!

ATMs around Munich belonging to the Bankcard-Servicenetz interbank network (federated query)

#defaultView:Map{"hide":["?atm","?geometry"], "layer": "?bankLabel"}

PREFIX lgdo: <http://linkedgeodata.org/ontology/>
PREFIX geom: <http://geovocab.org/geometry#>
PREFIX bif: <bif:>

SELECT ?atm ?geometry ?bank ?bankLabel WHERE {
  hint:Query hint:optimizer "None".
  
  SERVICE <http://linkedgeodata.org/sparql> {
    { ?atm a lgdo:Bank; lgdo:atm true. }
    UNION { ?atm a lgdo:Atm. }
    
    ?atm geom:geometry [geo:asWKT ?geometry];
         lgdo:operator ?operator.
    FILTER(bif:st_intersects(?geometry, bif:st_point(11.5746898, 48.1479876), 5)) # 5 km around Munich
  }
  
  BIND(STRLANG(?operator, "de") as ?bankLabel) 
  ?bank rdfs:label ?bankLabel.
  
  # bank is part of the Bankcard service network, either via an explicit statement or implicitly due to its legal form (unless explicitly excluded)
  { ?bank wdt:P527 wd:Q806724. }
  UNION { ?bank wdt:P1454 wd:Q5349747. }
  MINUS { wd:Q806724 wdt:P3113 ?bank. }
}

Try it!

Items geographically located around the Wikimedia Foundation office, sorted by distance

SELECT ?place ?location ?distance ?placeLabel WHERE {
    SERVICE wikibase:around { 
      ?place wdt:P625 ?location . 
      bd:serviceParam wikibase:center "Point(-122.402251 37.789246)"^^geo:wktLiteral . 
      bd:serviceParam wikibase:radius "1" . 
      bd:serviceParam wikibase:distance ?distance .
    } 
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} ORDER BY ?distance LIMIT 100

Try it!

Ten largest islands in the world

# Ten largest islands in the world
# Inspired by this infographic: https://redd.it/a6423t

#defaultView:ImageGrid
SELECT DISTINCT ?island ?islandLabel ?islandImage WHERE {
  # Instances of island (or of subclasses of island)
  ?island (wdt:P31/wdt:P279*) wd:Q23442.
  # Optionally with an image
  OPTIONAL { ?island wdt:P18 ?islandImage. }
  # Get the area of the island
  # Use the psn: prefix to normalize the values to a common unit of area
  ?island p:P2046/psn:P2046/wikibase:quantityAmount ?islandArea.
  # Use the label service to automatically fill ?islandLabel
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?islandArea)
LIMIT 10

Try it!

City gates in the Dutch province of Zeeland

select ?town ?townLabel ?gate ?gateLabel where {
  # Municipalities within the province 
  ?muni wdt:P31 wd:Q2039348;
        wdt:P131 wd:Q705.
  # Instances of city gate located within any of the municipalities
  ?gate wdt:P31 wd:Q82117;
        wdt:P131 ?muni;
  # The Location (usually Town) that the gate is in
        wdt:P276 ?town.
        
  SERVICE wikibase:label { bd:serviceParam wikibase:language "nl". }
}

Try it!


Demography

Birthplaces of humans named Antoine

# Coordinates of the birth places of people named Antoine
#defaultView:Map
SELECT ?item ?itemLabel ?coord
WHERE
{
  ?item wdt:P31 wd:Q5 .   # human
  ?item wdt:P735 wd:Q15235674.
  ?item wdt:P19 ?place.
  ?place wdt:P625 ?coord.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr". }
}

Try it!

Average lifespan by occupation

# Select the desired columns and get labels
SELECT ?occ ?occLabel ?avgAge ?avgBirthYear ?count
WHERE
{
  {
    # Group the people by their occupation and calculate age
    SELECT
      ?occ
        (count(?p) as ?count)
        (round(avg(?birthYear)) as ?avgBirthYear)
        (avg(?deathYear - ?birthYear) as ?avgAge)
    WHERE {
      {
        # Get people with occupation + birth/death dates; combine multiple birth/death dates using avg
        SELECT
          ?p
            ?occ
            (avg(year(?birth)) as ?birthYear)
            (avg(year(?death)) as ?deathYear)
        WHERE {
           ?p  wdt:P31 wd:Q5 ;
              wdt:P106 ?occ ;
              p:P569/psv:P569 [
                wikibase:timePrecision "9"^^xsd:integer ; # precision of at least year
                wikibase:timeValue ?birth ;
              ] ;
              p:P570/psv:P570 [
                wikibase:timePrecision "9"^^xsd:integer ; # precision of at least year
                wikibase:timeValue ?death ;
              ] .
        }
        GROUP BY ?p ?occ
      }
    }
    GROUP BY ?occ
  }
 
  FILTER (?count > 300) # arbitrary number to weed out values with 'few' observations
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . }
}
ORDER BY ASC(?avgAge)

Try it!

Items with the most birth dates

SELECT ?person (COUNT(?date) AS ?dateC) {
  ?person wdt:P569 ?date
}
GROUP BY ?person
HAVING (?dateC > 2)
ORDER BY DESC (?dateC)
LIMIT 100

Try it!

Things/people with most children

SELECT ?parent ?parentLabel ?count
WHERE
{
  {
    SELECT ?parent (COUNT(?child) AS ?count)
    WHERE
    {
      ?parent wdt:P40 ?child.
    }
    GROUP BY ?parent
    ORDER BY DESC(?count)
    LIMIT 10
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?count)
LIMIT 10

Try it!

Population growth in Suriname from 1960 onward

#defaultView:LineChart
SELECT ?year ?population {
  wd:Q730 p:P1082 ?p .
  ?p pq:P585 ?year ;
     ps:P1082 ?population .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
ORDER BY ?year

Try it!

Number of dead people by month since 2000

SELECT  ?yearmonth (COUNT(?person) as ?count)
WHERE
{
  ?person wdt:P31 wd:Q5;
          p:P570/psv:P570 [
                wikibase:timePrecision ?precision ;
                wikibase:timeValue ?date ;
              ] .
  BIND(CONCAT(STR(YEAR(?date)),"-",STR(MONTH(?date))) as ?yearmonth).
  FILTER( ?date >= "2000-01-01T00:00:00"^^xsd:dateTime )
  FILTER( ?precision >= "10"^^xsd:integer ) # precision of at least month
}
GROUP BY ?yearmonth

Try it!

Politics

Elections

The Netherlands

Candidates for the Dutch general election in 2017

The following query uses these:

  • Properties: Twitter username (P2002)  View with Reasonator View with SQID, P2035, candidacy in election (P3602)  View with Reasonator View with SQID, series ordinal (P1545)  View with Reasonator View with SQID, represents (P1268)  View with Reasonator View with SQID
    SELECT ?item ?itemLabel ?twitter ?LinkedIN ?politieke_partij ?politieke_partijLabel ?positie_op_lijst
    WHERE {
      ?item p:P3602 ?node .
        OPTIONAL { ?item wdt:P2002 ?twitter }
        OPTIONAL { ?item wdt:P2035 ?LinkedIN }
        ?node ps:P3602 wd:Q16061881 .
        OPTIONAL { ?node pq:P1545 ?positie_op_lijst }
        OPTIONAL { ?node pq:P1268 ?politieke_partij }
        OPTIONAL { ?node pq:P2035 ?LinkedIN }
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],nl" }
    }
    
Gender distribution in the candidates for the Dutch general election 2017

The following query uses these:

  • Properties: sex or gender (P21)  View with Reasonator View with SQID, candidacy in election (P3602)  View with Reasonator View with SQID, series ordinal (P1545)  View with Reasonator View with SQID, represents (P1268)  View with Reasonator View with SQID
    #Kandidaten voor de Nederlandse tk verkiezingen van 2017
    #defaultView:Dimensions
    SELECT ?positie_op_lijst ?genderLabel ?politieke_partijLabel WHERE {
      ?item p:P3602 ?node.
      ?item wdt:P21 ?gender.
      ?node ps:P3602 wd:Q16061881 .
      ?node pq:P1545 ?positie_op_lijst.
      ?node pq:P1268 ?politieke_partij.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],nl". }
    }
    
Candidates for the Dutch general election 2017 living in Antwerp, Belgium

The following query uses these:

  • Properties: residence (P551)  View with Reasonator View with SQID, Twitter username (P2002)  View with Reasonator View with SQID, P2035, candidacy in election (P3602)  View with Reasonator View with SQID, series ordinal (P1545)  View with Reasonator View with SQID, represents (P1268)  View with Reasonator View with SQID
    SELECT ?item ?itemLabel ?twitter ?LinkedIN ?politieke_partij ?politieke_partijLabel ?positie_op_lijst WHERE {
      ?item p:P3602 ?node.
      ?item wdt:P551 wd:Q12892.
      OPTIONAL { ?item wdt:P2002 ?twitter. }
      OPTIONAL { ?item wdt:P2035 ?LinkedIN. }
      ?node ps:P3602 wd:Q16061881.
      OPTIONAL { ?node pq:P1545 ?positie_op_lijst. }
      OPTIONAL { ?node pq:P1268 ?politieke_partij. }
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],nl". }
    }
    
Candidates for the Dutch general election 2017 living abroad

The following query uses these:

Features: Map (Q24515275)  View with Reasonator View with SQID

#defaultView:Map
SELECT ?item ?itemLabel ?coordinates WHERE {
  ?item p:P3602 ?node.
  ?item wdt:P551 ?residence .
  ?residence wdt:P17 ?country ;
             wdt:P625 ?coordinates .
  ?node ps:P3602 wd:Q16061881.
  FILTER (?country != wd:Q55)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],nl". }
}
Occupations of candidates of the Dutch general election 2017

The following query uses these:

  • Properties: sex or gender (P21)  View with Reasonator View with SQID, occupation (P106)  View with Reasonator View with SQID, candidacy in election (P3602)  View with Reasonator View with SQID, series ordinal (P1545)  View with Reasonator View with SQID, represents (P1268)  View with Reasonator View with SQID
    #Kandidaten voor de Nederlandse TK verkiezingen van 2017
    #defaultView:Dimensions
    SELECT ?positie_op_lijst ?genderLabel ?occupationLabel ?politieke_partijLabel WHERE {
      VALUES ?politieke_partij {wd:Q747910 wd:Q275441}
      ?item p:P3602 ?node.
      ?item wdt:P21 ?gender.
      ?item wdt:P106 ?occupation.
      ?node ps:P3602 wd:Q16061881.
      ?node pq:P1545 ?positie_op_lijst.
      ?node pq:P1268 ?politieke_partij.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],nl". }
    }
    

Gender balance of members of Irish parliament

SELECT ?genderlabel (COUNT(?genderlabel) as ?total)
WHERE
{
   ?subj wdt:P39 wd:Q654291  .
   ?subj wdt:P21 ?gender .
 
   ?gender rdfs:label ?genderlabel filter (lang(?genderlabel) = "en") .
   ?subj rdfs:label ?label filter (lang(?label) = "en")
}
GROUP BY ?genderlabel

Try it!

Assemblies by number of seats

SELECT DISTINCT ?item ?title ?seats ?jurisdiction (YEAR(?inception) AS ?start) (YEAR(?dissolution) AS ?end)
WHERE
{
  ?item wdt:P31/wdt:P279* wd:Q1752346 .
  OPTIONAL { ?item wdt:P1342 ?seats . }
  OPTIONAL {
    ?item wdt:P1001 ?j .
    ?j rdfs:label ?jurisdiction filter (lang(?jurisdiction) = "en") .
  }
  OPTIONAL { ?item wdt:P571 ?inception . }
  OPTIONAL { ?item wdt:P576 ?dissolution . }
  OPTIONAL { ?item rdfs:label ?title filter (lang(?title) = "en") . }
}
ORDER BY DESC(?seats) ?title

Try it!

List of countries by age of the head of government

#added by Jura1, rev. 2016-11-08
SELECT DISTINCT ?age ?country ?countryLabel ?hgovernment ?hgovernmentLabel
{
  ?country wdt:P31 wd:Q3624078 .
  FILTER NOT EXISTS {?country wdt:P31 wd:Q3024240}
  ?country p:P6 ?statement .    
  ?statement ps:P6 ?hgovernment .
  ?country wdt:P6 ?hgovernment .
  FILTER NOT EXISTS { ?statement pq:P582 ?x } 
  ?hgovernment wdt:P569 ?dob . BIND(YEAR(now())-YEAR(?dob) as ?age)
  FILTER(?age>=65)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
ORDER BY DESC(?age)

Try it!

Number of ministers who are themselves children of a minister, per country

SELECT ?cc (COUNT(DISTINCT ?child) AS ?number) {
  ?child wdt:P31 wd:Q5 ; # Looking for real humans and not fictional ones
         wdt:P39/wdt:P279* wd:Q83307 ;
         (wdt:P22|wdt:P25) [wdt:P39/wdt:P279* wd:Q83307] ;
         wdt:P27/wdt:P901 ?cc
}
GROUP BY ?cc
ORDER BY DESC(?number)

Try it!

Members of the French National Assembly born out of France

SELECT DISTINCT ?item ?itemLabel ?placeLabel ?countryLabel
WHERE
{
  ?item wdt:P39 wd:Q3044918 .
  ?item wdt:P19 ?place .
  ?place wdt:P17 ?country .
  FILTER NOT EXISTS { ?place wdt:P17 wd:Q142 . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "fr" . }
}
ORDER BY ?countryLabel ?itemLabel

Try it!

List of parliament buildings with pictures by country

#defaultView:ImageGrid
SELECT ?building ?buildingLabel ?country ?countryLabel ?picture
WHERE
{
  ?building wdt:P31 wd:Q7138926 .
  ?building wdt:P18 ?picture .
  OPTIONAL { ?building wdt:P17 ?country } .   #if available
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}
ORDER BY ?countryLabel
LIMIT 188

Try it!

Number of jurisdictions by driving side

SELECT ?sideLabel (COUNT(?jurisdiction) AS ?count)
WHERE
{
  ?jurisdiction wdt:P1622 ?side.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
GROUP BY ?sideLabel
ORDER BY ?sideLabel

Try it!

Timeline of mayors of Amsterdam, the Netherlands

#defaultView:Timeline
select ?mayor ?mayorLabel ?start ?end where {
  ?mayor p:P39 ?position.
  ?position ps:P39 wd:Q13423495;
            pq:P580 ?start;
            pq:P582 ?end.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],nl,en". }
}

Try it!

Current U.S. members of the Senate with district, party and date they assumed office

select ?senator ?senatorLabel ?districtLabel ?partyLabel ?assumedOffice (sample(?image) as ?image) where {
  # Get all senators
  ?senator p:P39 ?posheld; # With position held
           p:P102 ?partystatement. # And with a certain party
  
  # Get the party
  ?partystatement ps:P102 ?party.
  minus { ?partystatement pq:P582 ?partyEnd. } # but minus the ones the senator is no longer a member of
  minus { ?party wdt:P361 ?partOf. } # and the 'Minnesota Democratic–Farmer–Labor Party' and such
  
  # Check on the position in the senate
  ?posheld ps:P39 wd:Q4416090; # Position held is in the senate
           pq:P768 ?district;
           pq:P580 ?assumedOffice. # And should have a starttime
  
  minus { ?posheld pq:P582 ?endTime. } # But not an endtime 
  
  # Add an image
  optional { ?senator wdt:P18 ?image. }
         
  service wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} group by ?senator ?senatorLabel ?districtLabel ?partyLabel ?assumedOffice order by ?senatorLabel

Try it!

Economic and Business

Map of places of birth of dead economists, colour-coded by era

#defaultView:Map
SELECT DISTINCT ?person ?name ?birthplace ?birthyear ?coord ?layer WHERE {
{?person wdt:P106 wd:Q188094} UNION {?person wdt:P101 wd:Q8134}
?person wdt:P570 ?dod;
   wdt:P19 ?place .
?place wdt:P625 ?coord
OPTIONAL { ?person wdt:P569 ?dob }
BIND(YEAR(?dob) as ?birthyear)
BIND(IF( (?birthyear < 1700), "Pre-1700", IF((?birthyear < 1751), "1700-1750", IF((?birthyear < 1801), "1751-1800", IF((?birthyear < 1851), "1801-1850", IF((?birthyear < 1901), "1851-1900", IF((?birthyear < 1951), "1901-1950", "Post-1950") ) ) ) )) AS ?layer )
?person rdfs:label ?name filter (lang(?name) = "en")
?place rdfs:label ?birthplace filter (lang(?birthplace) = "en")
} ORDER BY ?birthyear

Try it!

Distinct Billionaires

# 2018-05-10: 93 results

SELECT ?locationLabel ?item ?itemLabel (MAX(?billions) as ?billions)
WHERE
{
  ?item wdt:P2218 ?worth.
  ?item wdt:P19 ?location .
  
  FILTER(?worth>1000000000).
  BIND(?worth/1000000000 AS ?billions).
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en,de". }
}
GROUP BY ?locationLabel ?item ?itemLabel
ORDER BY DESC(?billions)

Try it!

Science

Biology and Medicine

Diseases

The number of existing translations for diseases in Wikidata

Items used: disease (Q12136)

SELECT ?disease ?doid ?enLabel (count(?language) as ?languages)
WHERE
{
  ?disease wdt:P699 ?doid ;
             rdfs:label ?label ;
             rdfs:label ?enLabel .
    FILTER (lang(?enLabel) = "en")
   
    BIND (lang(?label) AS ?language)
}
group by ?disease ?doid ?enLabel
order by desc(?languages)

Try it!

A network of Drug-disease interactions on infectious diseases (Source: Disease Ontology, NDF-RT and ChEMBL)
#defaultView:Graph
SELECT DISTINCT ?item ?itemLabel ?rgb ?link
WHERE
{
  VALUES ?toggle { true false }
  ?disease wdt:P699 ?doid;
           wdt:P279+ wd:Q18123741;
           wdt:P2176 ?drug.
  ?drug rdfs:label ?drugLabel.
    FILTER(LANG(?drugLabel) = "en").
  ?disease rdfs:label ?diseaseLabel.
    FILTER(LANG(?diseaseLabel) = "en").
  BIND(IF(?toggle,?disease,?drug) AS ?item).
  BIND(IF(?toggle,?diseaseLabel,?drugLabel) AS ?itemLabel).
  BIND(IF(?toggle,"FFA500","7FFF00") AS ?rgb).
  BIND(IF(?toggle,"",?disease) AS ?link).
}

Try it!

The number of Wikidata items on Diseases and the percentage of those with a pointer to the Disease Ontology
SELECT (COUNT(?disease) AS ?total) (SUM(?ref) AS ?byDO) (100*?byDO/?total AS ?percent)
WHERE
{
  {?disease wdt:P31 wd:Q12136 }
  UNION
  {?disease wdt:P279 wd:Q12136 .}
  OPTIONAL {
    ?disease p:P699 ?statement.
    BIND(1 AS ?ref).
  }
}

Try it!

Genes

Human genes updated this week
SELECT DISTINCT ?item ?ncbi_gene ?date_modified
WHERE
{
  ?item wdt:P351 ?ncbi_gene ;
          wdt:P703 wd:Q15978631 ;
          schema:dateModified ?date_modified .
    BIND (now() - ?date_modified as ?date_range)
    FILTER (?date_range < 8)
}

Try it!

Variants

Counts of gene-variant types sourced from the CIViC database
#defaultView:BarChart
SELECT  ?variant_typeLabel (count(?variant_typeLabel) as ?counts)
WHERE
{
  ?item wdt:P3329 ?civic_id ;
          wdt:P31 ?variant_type .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
GROUP BY ?variant_typeLabel
ORDER BY ?counts

Try it!

Which variant of which gene predicts a positive prognosis in colorectal cancer
SELECT ?geneLabel ?variantLabel
WHERE
{ 
  VALUES ?disease {wd:Q188874}
    ?variant wdt:P3358 ?disease ; # P3358 Positive prognostic predictor
          wdt:P3433 ?gene . # P3433 biological variant of
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}

Try it!

Variants that are associated with renal cell carcinoma
# variants that are associated with renal cell carcinoma
SELECT DISTINCT ?civic_id ?item ?itemLabel
WHERE
{
  VALUES ?property {
                      wdt:P3356 # positive diagnostic predictor
                      wdt:P3357 # negative diagnostic predictor
                      wdt:P3358 # positive prognostic predicator
                      wdt:P3359 # negative prognostic predictor
                     }
    ?item wdt:P3329 ?civic_id .
    {?item  ?property wd:Q1164529.} # wd:Q1164529 = renal cell carcinoma
    UNION
    {?item p:P3354 ?o . # positive therapeutic predictor
     ?o pq:P2175 wd:Q1164529 .}
    UNION
    {?item p:P3354 ?o . # negative therapeutic predictor
     ?o pq:P2175 wd:Q1164529 .}
     
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}

Try it!

PubMed references in CIViCdb
# variants that are associated with renal cell carcinoma
SELECT DISTINCT  ?reference ?referenceLabel ?pmid
WHERE
{
  ?item wdt:P3329 ?civicId ;
          ?property  ?object .
    ?object prov:wasDerivedFrom ?provenance .
    ?provenance pr:P248 ?reference .
    ?reference wdt:P31 wd:Q13442814 ;
               wdt:P698 ?pmid .
   
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}

Try it!

Variant counts by predictor type
#defaultView:BubbleChart
SELECT  ?propertyLabel (count(?prognostic_type) as ?counts)
WHERE
{
  VALUES ?prognostic_type {wdt:P3354 wdt:P3355 wdt:P3356 wdt:P3357 wdt:P3358 wdt:P3359}
    ?item wdt:P3329 ?civic_id ;
          ?prognostic_type ?prognostic_value .
    ?property wikibase:directClaim ?prognostic_type . 
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
GROUP BY ?propertyLabel ?prognostic_typeLabel
ORDER BY ?counts

Try it!

Proteins

Get Wikidata - UniprotId mappings for homo sapiens
SELECT ?item ?itemLabel ?uniprotid ?tax_node
WHERE
{
  ?item wdt:P352 ?uniprotid ;
          wdt:P703 wd:Q15978631 .
   
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}

Try it!

Metabolites

Metabolites and the species where they are found in
PREFIX pr: <http://www.wikidata.org/prop/reference/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX prov: <http://www.w3.org/ns/prov#>

SELECT ?compound ?compoundLabel ?speciesLabel ?sourceLabel ?doi ?wpid WHERE {
  ?compound wdt:P31 wd:Q11173.
  MINUS { ?compound wdt:P31 wd:Q8054. }
  ?compound p:P703 ?statement.
  ?statement rdf:type wikibase:BestRank.
  ?statement ps:P703 ?species.
  OPTIONAL {
    ?statement (prov:wasDerivedFrom/pr:P248) ?source.
    OPTIONAL { ?source wdt:P2410 ?wpid. }
    OPTIONAL { ?source wdt:P356 ?doi. }
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY ASC(?compound)

Try it!

Metabolite-metabolite interactions (mostly conversions) and their pKa change

Federated query using the WikiPathways SPARQL endpoint to retrieve interaction information. The dimensions plot show the pKa changes during metabolite-metabolite interaction. It must be noted here that many very basic or very acidic are reported in pathways as the uncharged structure, whereas in normal biological pathways these compounds are charged and then have quite different pKa charges.

#defaultView:Dimensions
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX wp:    <http://vocabularies.wikipathways.org/wp#>
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT DISTINCT ?wpid ?metaboliteLabel ?pKa ?pKa2 ?metabolite2Label ?wpid2
WITH {
  SELECT ?wpid ?source_pathway ?metabolite ?pKa ?pKa2 ?metabolite2 ?wpid2
  WHERE {
    # VALUES ?wpid { "WP550" }
    ?pathway wdt:P2410 ?wpid ;
             wdt:P527 ?metabolite ;
             wdt:P2888 ?source_pathway .
    ?metabolite wdt:P1117 ?pKa .

    SERVICE <http://sparql.wikipathways.org/sparql> {
      ?wp_mb1 wp:bdbWikidata ?metabolite .
      ?wp_mb1 dcterms:isPartOf ?interaction .
      ?interaction rdf:type wp:Interaction .
      ?wp_mb2 dcterms:isPartOf ?interaction .
      ?wp_mb2 wp:bdbWikidata ?metabolite2 .
      FILTER (?wp_mb1 != ?wp_mb2)
    }
  }
} AS %result
WHERE {
  INCLUDE %result
  ?metabolite2 wdt:P1117 ?pKa2 .
  ?pathway2 wdt:P2410 ?wpid2 ;
             wdt:P527 ?metabolite2 ;
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Try it!

Taxon

Asterophryinae parent taxon reverse graph
#defaultView:Graph
PREFIX gas: <http://www.bigdata.com/rdf/gas#>

SELECT ?item ?itemLabel ?pic ?linkTo
WHERE
{
  SERVICE gas:service {
    gas:program gas:gasClass "com.bigdata.rdf.graph.analytics.SSSP" ;
                gas:in wd:Q1968598;
                gas:traversalDirection "Reverse" ;
                gas:out ?item ;
                gas:out1 ?depth ;
                gas:maxIterations 3 ;
                gas:linkType wdt:P171 .
  }
  OPTIONAL { ?item wdt:P171 ?linkTo }
  OPTIONAL { ?item wdt:P18 ?pic }
  SERVICE wikibase:label {bd:serviceParam wikibase:language "en" }
}

Try it!

Pathways

All human pathways from Wikipathways
SELECT ?pathway ?pathwayLabel ?wpid WHERE {
   ?pathway wdt:P2410 ?wpid ;
            wdt:P703 wd:Q15978631 .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}

Try it!

Biomarkers in Wikidata which interact with proteins in human pathways from Wikipathways
prefix void:  <http://rdfs.org/ns/void#> 
prefix pav:   <http://purl.org/pav/> 
prefix xsd:   <http://www.w3.org/2001/XMLSchema#> 
prefix freq:  <http://purl.org/cld/freq/> 
prefix biopax: <http://www.biopax.org/release/biopax-level3.owl#> 
prefix skos:  <http://www.w3.org/2004/02/skos/core#> 
prefix rdfs:  <http://www.w3.org/2000/01/rdf-schema#> 
prefix rdf:   <http://www.w3.org/1999/02/22-rdf-syntax-ns#> 
prefix gpml:  <http://vocabularies.wikipathways.org/gpml#> 
prefix wp:    <http://vocabularies.wikipathways.org/wp#> 
prefix dcterms: <http://purl.org/dc/terms/> 
prefix wprdf: <http://rdf.wikipathways.org/> 
prefix prov:  <http://www.w3.org/ns/prov#> 
prefix foaf:  <http://xmlns.com/foaf/0.1/> 
prefix dc:    <http://purl.org/dc/elements/1.1/> 

SELECT DISTINCT ?biomarkerLabel ?proteinLabel ?geneID ?WP_gene ?PathwayID ?PathwayName #results that are displayed.
WHERE {
  VALUES ?biomarker {wd:Q420633 wd:Q27125809 wd:Q422462} #you can add more biomarkers here if needed, separated by a space.
  ?biomarker wdt:P31 wd:Q11173. #Stating that all biomarkers have to be "instance of" "chemical compound" (you could ommit this, but query will probably take longer).
  ?biomarker wdt:P638 ?pdbID .  #Checking if a biomarker has a Protein Databank ID (PDB) -> meaning the metabolite can interact with a protein.
  ?protein wdt:P31 wd:Q8054 . #Stating that all proteins are "instance of" "protein"
  ?protein wdt:P638 ?pdbID . #Checking which proteins have a PDB ID, which we queried previously in relationship to the biomarkers.
  ?protein wdt:P702 ?gene . #Connecting the protein to a gene ("encoded by" relationship) -> to get an identifier we can use later in federated WikiPathways query.
  ?gene wdt:P703 wd:Q15978631 . #Now removing all genes that are not found in species "Homo sapiens". -> This info is not always available for proteins in WikiData.
  ?gene wdt:P2888 ?geneID . #Getting the "exact match" identifier for the gene, related to the protein, related to the biomarker.
    
  SERVICE <http://sparql.wikipathways.org/sparql> { #Connecting to the WikiPathways SPARQL endpoint.
     ?WP_pathway a wp:Pathway . #Stating a ?WP_pathway is indeed a pathway in the WikiPathways RDF .
     ?WP_pathway wp:organismName "Homo sapiens"^^xsd:string . #Removing all PWs not for species Homo sapiens.
     ?WP_pathway dc:identifier ?PathwayID . #Query the identifier of the pathway in WPs.
     ?WP_pathway dc:title ?PathwayName . #Obtaining the name of the pathway. 
    
     ?WP_gene a wp:Protein . #Stating that a ?WP_gene is a Protein DataNode (you could ommit this, to also get all DataNodes modeled as GeneProducts out, but query will take longer).
     ?WP_gene wp:bdbEntrezGene ?geneID . #Connecting the previously queried "exact match" from WikiData to the NCBI/Entrez Gene ID in WPs. 
     ?WP_gene dcterms:isPartOf ?WP_pathway . #Connecting the WP_gene to the WP_pathway.
     
   }
 OPTIONAL {?biomarker rdfs:label ?biomarkerLabel. #Create a label (aka name) for the biomarkers in WikiData, without using the service query. 
FILTER(LANG(?biomarkerLabel) = "en").
}
   OPTIONAL {?protein rdfs:label ?proteinLabel. #Create a label(aka name) for the proteins in WikiData, without using the service query.
FILTER(LANG(?proteinLabel) = "en").
}
 
}
ORDER BY DESC (?biomarkerLabel) #Order results for biomarkers

Try it!

Ranking of most cited work in WikiPathways
SELECT ?citation ?citationLabel (count(?pathway) as ?times_cited) WHERE {
  ?pathway wdt:P2410 ?WikiPathwaysID ;
           wdt:P2860 ?citation .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
  }
GROUP BY ?pathway ?citation ?citationLabel

Try it!

Gene and metabolite counts per pathway
#Gene and metabolite counts per path
#defaultView:ScatterChart
SELECT ?path ?genes ?metabolites ?pathway WHERE {
  {SELECT DISTINCT ?path (COUNT(?pwPart) AS ?genes) WHERE {
      ?path wdt:P2410 ?WikipathsID.
      ?path wdt:P527 ?pwPart.
      ?pwPart wdt:P31 wd:Q7187.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    GROUP BY ?path ?genes
  }
  {SELECT DISTINCT ?path (COUNT(?pwPart) AS ?metabolites) WHERE {
      ?path wdt:P2410 ?WikipathsID.
      ?path wdt:P527 ?pwPart.
      ?pwPart wdt:P31 wd:Q11173.
      SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    }
    GROUP BY ?path ?metabolites
  }
  OPTIONAL { ?path rdfs:label ?pathway. }
}
ORDER BY DESC(?genes)

Try it!

Biological pathways with protein structures in the PDB database
SELECT ?pathway ?pathwayLabel ?WikiPathways ?Reactome (COUNT(DISTINCT ?protein) as ?count) WHERE {
  VALUES ?pathwayType { wd:Q4915012 wd:Q2996394 }
  ?pathway wdt:P31 ?pathwayType .
  { ?pathway wdt:P527/wdt:P688 ?protein . } UNION { ?pathway wdt:P527 ?protein . }
  ?protein wdt:P638 ?PDBID .
  OPTIONAL { ?pathway wdt:P2410 ?WikiPathways }
  OPTIONAL { ?pathway wdt:P3937 ?Reactome }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
} GROUP BY ?pathway ?pathwayLabel ?WikiPathways ?Reactome
  ORDER BY DESC(?count)

Try it!

Integration queries (with other sources)
Get known variants reported in CIViC database (Q27612411) of genes reported in a Wikipathways pathway: Bladder Cancer (Q30230812)

The following query uses these: