Wikidata:Request a query

Request a query
Fishing in the Wikidata river requires both an idea where to look for fish and a suitable fishing method. If you have the former, this page can help you find the latter.

This is a page where SPARQL 1.1 Query Language (Q32146616) queries can be requested. Please provide feedback if a query is written for you.

For sample queries, see Examples and Help:Dataset sizing. Property talk pages include also summary queries for these.

For help writing your own queries, or other questions about queries, see Wikidata talk:SPARQL query service/queries and Wikidata:SPARQL query service/query optimization.

Help resources about Wikidata Query Service (Q20950365) and SPARQL: Wikidata:SPARQL query service/Wikidata Query Help and Category:SPARQL.

To report an issue about the Query Service (interface, results views, export...) please see Wikidata:Contact the development team/Query Service and search.

On this page, old discussions are archived. An overview of all archives can be found at this page's archive index. The current archive is located at 2021/02.

Italian municipalities with latest population figures not set to preferred rankEdit

I'm looking for instances of comune of Italy (Q747074) where there are multiple values for population (P1082), but where the most recent (point in time (P585)) value is not set to preferred rank. - 4ing (talk) 09:56, 29 January 2021 (UTC)

@4ing: Two queries for you. First is the new dates that are not of BestRank, and the second is the old dates that are of BestRank. Both includes GUIDs for the claims, so that it becomes easy to use e.g. wikibase-cli to tweak the rank for the claims.
SELECT ?item ?itemLabel ?date ?rank ?stat with {
SELECT ?item (max(?date_) as ?date) 
WHERE 
{
  ?item wdt:P31 wd:Q747074.
  ?item p:P1082 ?stat.
  ?stat pq:P585 ?date_.
  } group by ?item } as %i
where
{
  include %i
  ?item p:P1082 ?stat.
  ?stat pq:P585 ?date.
  filter not exists {    ?stat a wikibase:BestRank. }
  ?stat wikibase:rank ?rank.      
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Try it!
SELECT ?item ?itemLabel ?date_old ?rank ?stat with {
SELECT ?item (max(?date_) as ?date) 
WHERE 
{
  ?item wdt:P31 wd:Q747074.
  ?item p:P1082 ?stat.
  ?stat pq:P585 ?date_.
  } group by ?item } as %i
with { SELECT ?item where
{
  include %i
  ?item p:P1082 ?stat.
  ?stat pq:P585 ?date.
  filter not exists {    ?stat a wikibase:BestRank. }
  ?stat wikibase:rank ?rank.      
}  } as %j
where
{
  include %j
  ?item p:P1082 ?stat.
  ?stat pq:P585 ?date_old.
  ?stat a wikibase:BestRank. 
  ?stat wikibase:rank ?rank.      
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Try it! --Tagishsimon (talk) 13:22, 29 January 2021 (UTC)
@Tagishsimon: Thanks for your swift response. The issue was less frequent than I expected - it applies to 419 out of 7918 instances of comune of Italy (Q747074) (I've manually corrected a few entries earlier today based on a list generated by ListeriaBot. Preferred rank shouldn't always be assigned to the latest value due to lack of source/poor source, lack of determination method (P459) etc. However, items with latest population figures dated 2018-01-01 (applies to most items), should have this value set as preferred rank since it is properly sourced and includes relevant qualifiers. I don't have the skills (yet) to use wikibase-cli to change the ranks. - 4ing (talk) 21:34, 29 January 2021 (UTC)


@4ing: So these all look good; at the least we have determination and a reference URL. I can run wikibase-cli over these if you're happy, and remove preferred from prior dates.
SELECT ?item ?itemLabel ?date ?determination ?ref ?rank ?stat with {
SELECT ?item (max(?date_) as ?date) 
WHERE 
{
  ?item wdt:P31 wd:Q747074.
  ?item p:P1082 ?stat.
  ?stat pq:P585 ?date_.
  } group by ?item } as %i
where
{
  include %i
  ?item p:P1082 ?stat.
  ?stat pq:P585 ?date.
  optional {?stat pq:P459 ?determination. }
  optional {?stat prov:wasDerivedFrom/pr:P854 ?ref.}
  filter not exists {    ?stat a wikibase:BestRank. }
  ?stat wikibase:rank ?rank.      
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Try it! --Tagishsimon (talk) 21:54, 29 January 2021 (UTC)
@Tagishsimon: No, not all of them are good. All with date 2018-01-10 should be good, but rank on e.g. Gela (Q39971) should not be changed, since the newest value of population (P1082) is missing both point in time (P585), determination method (P459) and a reference. I think the query should be modified to instances of comune of Italy (Q747074) where there are multiple values for population (P1082), the most recent value is dated 2018-01-01, but the most recent value does not have the preferred rank. It would would solve 95 % of the problem, the remaining 5 % could be checked manually. - 4ing (talk) 22:41, 29 January 2021 (UTC)
@4ing: Here is a query which finds instances of comune of Italy (Q747074) where there is a value for P1082 with preferred rank, and another value for P1082 with normal rank that also meets these conditions: It must have a determination method (P459) qualifier, it must have a newer date, it must have a source with contains reference URL (P854). For various reasons 3 comunes (Avellino (Q13433), Andria (Q13486), Agnadello (Q42983)) have more than one result in the query. You might want to fix these manually. Then maybe the rest can fixed by a tool if you like the results.
SELECT ?item ?itemLabel ?date_preferred_rank ?date_newer ?method_newerLabel ?source_URL
WHERE 
{
  ?item wdt:P31 wd:Q747074 .

  # Find a P1082 statement with preferred rank
  ?item p:P1082 ?stat_preferred_rank .
  ?stat_preferred_rank wikibase:rank wikibase:PreferredRank .
  ?stat_preferred_rank pq:P585 ?date_preferred_rank .

  # Find a P1082 statement with normal rank, P459 qualificator, source with P854, and a newer date
  ?item p:P1082 ?stat_newer .
  ?stat_newer wikibase:rank wikibase:NormalRank .
  ?stat_newer pq:P585 ?date_newer .
  FILTER (?date_newer > ?date_preferred_rank)
  ?stat_newer pq:P459 ?method_newer .
  ?stat_newer prov:wasDerivedFrom ?source_newer .
  ?source_newer pr:P854 ?source_URL .

  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en,it" . }
}
Try it! --Dipsacus fullonum (talk) 05:00, 30 January 2021 (UTC)

@Dipsacus fullonum: I've manually corrected the three items you listed, in addition to Verona (Q2028), which had two values marked with preferred rank. The remaining 405 items should have corrected the rank. @Tagishsimon: If you could run wikibase-cli on these, I would definitely be happy! - 4ing (talk) 21:34, 30 January 2021 (UTC)

@4ing: Doing that right now. You might want to check Alpette (Q8993) by hand - it had a 2017 and 2019 marked as preferred. I suspect you'll want 2018 to be preferred now, but I've not implemented that. --Tagishsimon (talk) 14:19, 31 January 2021 (UTC)
@Tagishsimon: Thanks for excellent work. Alpette (Q8993) is actually taking us to the next issue: Istat (Q214195) is not a proper value for stated in (P248), it should have been publisher (P123). Relevant reference URL (P854) would be http://demo.istat.it/pop2017/index3.html for population (P1082) with point in time (P585) 2017-01-01, http://demo.istat.it/pop2018/index3.html for 2018-01-01, http://demo.istat.it/pop2019/index3.html for 2019-01-01 and http://demo.istat.it/pop2020/index3.html for 2020-01-01. In addition, many population (P1082) with point in time (P585) 2017-01-01 should have changed reference URL (P854) from http://www.demo.istat.it/pop2017/index3.html (dead link) to http://demo.istat.it/pop2017/index3.html. Would you be able to set up the relevant queries (it is limited to comune of Italy (Q747074))? - 4ing (talk) 21:51, 31 January 2021 (UTC)
In adition, I think there are instances of stated in (P248) and publisher (P123), with value Istat (Q214195), being set as qualifiers, not reference. - 4ing (talk) 21:58, 31 January 2021 (UTC)
And last addition for today: Tavagnacco (Q53378) and several other items have two point in time (P585) for the same value of population (P1082). - 4ing (talk) 22:08, 31 January 2021 (UTC)
@4ing: I've sorted out items having two point in time (P585) for the same value of population (P1082), and items having http://www.demo.istat.it/pop2017/index3.html. I'll have a look some more tomorrow. --Tagishsimon (talk) 02:38, 1 February 2021 (UTC)
Thanks, this looks excellent! Be aware that in instances like Bagnolo Mella (Q103462), preferred rank should be set. - 4ing (talk) 08:07, 1 February 2021 (UTC)
Inefficient to revisit rank until the underlying data is sorted out, was my thinking. --Tagishsimon (talk) 10:53, 1 February 2021 (UTC)

@Tagishsimon: Do you have any plans to complete this task? Most important is to correct the wrong use of stated in (P248)? - 4ing (talk) 09:08, 15 February 2021 (UTC)

Articles that are missing in a certain languageEdit

Hello everyone, I tried to write a SPARQL query to get a list of articles that are not on it.wiki but are on other wikis, then I would sort it descendingly by number of wikis where the entry appears. I didn't succeed. My intention is to see which articles are most "urgent" to write on the Italian wiki. I imagine that the final list will be very long, but even just the first 100 results would be enough

The biggest problem is to know which items represent "articles". A simple query like this:
SELECT ?item ?itemLabel ?sitelinks
WHERE
{
  {
    SELECT ?item ?sitelinks
    WHERE
    {
      ?item wikibase:sitelinks ?sitelinks .
      hint:Prior hint:rangeSafe true .
      FILTER (?sitelinks >= 100 )
      MINUS
      {
        ?itwiki_link schema:about ?item .
        ?itwiki_link schema:isPartOf <https://it.wikipedia.org/> . 
      }
    }
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en,it" . }
}
ORDER BY DESC(?sitelinks)
Try it! will find all items with 100+ sitelinks but not on itwiki. Most, however, are for templates, categories, modules and other wiki pages that aren't articles. --Dipsacus fullonum (talk) 15:19, 11 February 2021 (UTC)
Okay, thank you so much for your quick answer. This is a good starting point for sure

Taxa, Wikispecies links and synonymyEdit

Hi, below is a query showing the genera of Echinodermata and showing potential Wikispecies links:

#genera of Echinodermata showing potential Wikispecies links

SELECT ?item ?itemLabel ?rankLabel ?speciessitelink
WHERE 
{
  ?item wdt:P171/wdt:P171* wd:Q44631.
  ?item wdt:P105 ?rank.
  ?item wdt:P105 wd:Q34740.
  OPTIONAL { ?speciessitelink schema:about ?item; schema:isPartOf <https://species.wikimedia.org/> }
    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  
} order by ?rankLabel ?itemLabel

Try it!

In addition to the query above I would like to highlight which taxa are listed as synonyms and from which items they are synonyms, the relation is:

Freyella (Q3469379) taxon synonym (P1420) = Freyellidea (Q105427219)

Can someone help me please? Christian Ferrer (talk) 16:24, 11 February 2021 (UTC)

@Christian Ferrer: Do you mean like this just listing statements with P1420:
#genera of Echinodermata showing potential Wikispecies links

SELECT DISTINCT ?item ?itemLabel ?rankLabel ?speciessitelink ?synonym ?synonymLabel
WHERE
{
  ?item wdt:P171+ wd:Q44631 .
  ?item wdt:P105 ?rank .
  ?item wdt:P105 wd:Q34740 .
  OPTIONAL { ?speciessitelink schema:about ?item ; schema:isPartOf <https://species.wikimedia.org/> . }
  OPTIONAL { ?item wdt:P1420 | ^wdt:P1420 ?synonym . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" . }
}
order by ?rankLabel ?itemLabel
Try it!
Or would you something grouped by non-synonym taxons with a list of all synonym in each row? --Dipsacus fullonum (talk) 17:22, 11 February 2021 (UTC)
@Dipsacus fullonum: thanks you, I would want the opposite approach than what you offer me. E.g. within the results of that query the first that show a synonym is Acodontaster (Q3198001)Heuresaster (Q60672803), the issue is that when we are at the line concerning Heuresaster (Q60672803) we don't have the info that this taxon is considered as a synonym of Acodontaster (Q3198001). And this is that thing I would want. Christian Ferrer (talk) 19:02, 11 February 2021 (UTC)
@Christian Ferrer: I added a change to also use the reverse path for P1420 (^wdt:P1420) in the query above. Do the query what you want now? --Dipsacus fullonum (talk) 06:08, 12 February 2021 (UTC)
@Dipsacus fullonum: yes it is exactly what I want, thanks you very much! Christian Ferrer (talk) 06:12, 12 February 2021 (UTC)

For an International Women's Day campaign: A long list of high quality photos used on Wikipedia articles about womenEdit

Hi all

I'm putting together a social media campaign for March 8th, International Women's Day to encourage people to suggest women who should be on Wikidata/Wikipedia. For this I need a large selection of high quality portrait photographs of women but I've no idea how I would go about collating a list, I think the requirements would be something like:

  1. Portrait photos, like the kind that appear in infoboxes
  2. High quality, I know there are some different templates used on Commons for this like Featured_pictures_on_Wikimedia_Commons, Quality_images, Valued_images
  3. Geographically diverse
  4. Don't have to be all 'famous' women, so not just 'most viewed articles'

Does anyone have any idea how to collate something like this? I'm very happy to get a giant pile to sift through.

Thanks very much

John Cummings (talk) 23:29, 11 February 2021 (UTC)

@John Cummings: Here's an approach which seems to work for Valued images and may work for Quality and Featured (if perhaps the limit value is tweaked up or down). There may be better appeoaches, but, bear of small brain &c --Tagishsimon (talk) 01:00, 12 February 2021 (UTC)
#defaultView:ImageGrid
SELECT ?file ?image ?depicts ?depictsLabel with { SELECT ?file ?image ?depicts where {
  hint:Query hint:optimizer "None".
  ?file wdt:P6731 wd:Q63348040 . # valued
#  ?file wdt:P6731 wd:Q63348069 . # quality
#  ?file wdt:P6731 wd:Q63348049 . # featured
  ?file schema:contentUrl ?url .
  ?file wdt:P180 ?depicts .
  BIND(IRI(CONCAT("http://commons.wikimedia.org/wiki/Special:FilePath/", wikibase:decodeUri(SUBSTR(STR(?url),53)))) AS ?image)
} limit 10000 } as %i
WHERE
  {
    include %i
    SERVICE <https://query.wikidata.org/sparql>
    {
      ?depicts wdt:P21 wd:Q6581072.
  #    SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    }
  }
Try it!
Tagishsimon thanks so much for this, can you think of any ways to produce a larger number of images? This is a great start but the list is not as long as I was expecting. --John Cummings (talk) 13:06, 12 February 2021 (UTC)

ESRB video game ID (P8303)Edit

I need a query for items with ESRB video game ID (P8303) where:

--Trade (talk) 12:47, 12 February 2021 (UTC)

@Trade: Do you want truthy (best rank) statements only or all statements? --Dipsacus fullonum (talk) 13:10, 12 February 2021 (UTC)
All --Trade (talk) 13:11, 12 February 2021 (UTC)
@Trade:
# ?items with P8303 statements of all ranks with novalue or somevalue, and P577 at 2020-08-12 or earlier
SELECT ?item ?itemLabel ?release_date ?value
{
  ?item wdt:P577 ?release_date .
  hint:Prior hint:rangeSafe true .
  FILTER ( ?release_date <= "+2020-08-12T00:00:00Z"^^xsd:dateTime )
  ?item p:P8303 ?statement .
  {
    ?statement a wdno:P8303 .
    BIND ("novalue" as ?value)
  }
  UNION
  {
    ?statement ps:P8303 ?v .
    FILTER wikibase:isSomeValue(?v)
    BIND ("somevalue" as ?value)
  }      
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" . }
}
Try it! --Dipsacus fullonum (talk) 14:04, 12 February 2021 (UTC)
Thanks--Trade (talk) 14:43, 12 February 2021 (UTC)

Show only the references that have a specific roleEdit

#genera of Echinodermata showing potential: authors, fisrt description, Wikispecies links and synonymy

SELECT DISTINCT ?item ?itemLabel ?author ?firstDescription ?speciesSitelink ?isSynonymOf ?isSynonymOfLabel
WHERE
{
  ?item wdt:P171+ wd:Q44631 .
  ?item wdt:P105 ?rank .
  ?item wdt:P105 wd:Q34740 .
  OPTIONAL { ?item p:P225 ?st . 
    ?st pq:P405 ?author . }
  OPTIONAL { ?item p:P225 ?statement .
    ?statement prov:wasDerivedFrom ?reference .
    ?reference pr:P248 ?firstDescription .
    ?reference pr:P6184 wd:Q1361864 . }
  OPTIONAL { ?speciesSitelink schema:about ?item ; schema:isPartOf <https://species.wikimedia.org/> . }
  OPTIONAL { ?item ^wdt:P1420 ?isSynonymOf . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" . }
}
order by ?itemLabel

Try it!

@Christian Ferrer: I made a change to the query above. It introduces the variable ?reference to make sure that the two triples with pr: predicates use the same reference. --Dipsacus fullonum (talk) 14:27, 12 February 2021 (UTC)
Excellent, thanks you. It's easier now for me to see where data is missing. Christian Ferrer (talk) 15:22, 12 February 2021 (UTC)

Map in defined languageEdit

Hello,

I'm looking at statues in Helsinki in Wikidata and what information is available about them in Finland's national language Swedish. If I put them on a map with this query, the map is in Finnish. Is there any way to get the map to show the Swedish names of the streets and neighbourhoods - which I know is available in OSM? If not, what is the right place to suggest this improvement?

Thanks! Robertsilen (talk) 08:51, 15 February 2021 (UTC)

GROUP_CONCATEdit

Hello, I'have a probleme with a requete

when i write

SELECT ?personnes ?personnesLabel

 (GROUP_CONCAT(DISTINCT(?occupation); separator=", ") as ?LeursoccupationsLabel)
 WHERE {
 SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
 
 VALUES ?metier {
   wd:Q20814940
   wd:Q45748643
   wd:Q3542795
 }
 ?personnes wdt:P106 ?metier;
   wdt:P21 wd:Q6581072.
 OPTIONAL { ?personnes wdt:P106 ?occupation. }

} GROUP BY ?personnes ?personnesLabel

?LeursoccupationsLabel, I'have "http://www.wikidata.org/entity/Q191493, http://www.wikidata.org/entity/Q897317, http://www.wikidata.org/entity/Q16947675, http://www.wikidata.org/entity/Q45748643" and i want "caviste, oenologie...".

Can you help me ? Thanks

You cannot use a label obtained by the automatic mode of the label service as a function argument, but have to switch to the manual mode. It is explained in the user manual at mw:Wikidata Query Service/User Manual#Label service.
SELECT ?personnes ?personnesLabel
 (GROUP_CONCAT(DISTINCT(?occupationLabel); separator=", ") as ?LeursoccupationsLabel)
WHERE {
 SERVICE wikibase:label {
   bd:serviceParam wikibase:language "[AUTO_LANGUAGE],fr,en" .
   ?personnes rdfs:label ?personnesLabel.
   ?occupation rdfs:label ?occupationLabel.
 }

 VALUES ?metier {
   wd:Q20814940
   wd:Q45748643
   wd:Q3542795
 }
 ?personnes wdt:P106 ?metier;
   wdt:P21 wd:Q6581072.
 OPTIONAL { ?personnes wdt:P106 ?occupation. }
}
GROUP BY ?personnes ?personnesLabel ?LeursoccupationsLabel
Try it! --Dipsacus fullonum (talk) 15:24, 15 February 2021 (UTC)
thank you Silanoc (talk) 15:43, 15 February 2021 (UTC)

Value without referenceEdit

Hello, I would like to find the list of woman dead in Paris before 1900 without reference for the date, but I don't succeed..

#Women dead in Paris before 1900 without reference for the date
SELECT ?item ?itemLabel ?date 
WHERE 
{
  ?item wdt:P21 wd:Q6581072;
        wdt:P20 wd:Q90;
        wdt:P570 ?date;
  MINUS {?item wdt:P31 wd:Q95074}.
  FILTER ( year(?date) < 1900 ).
  MINUS {?date pr:[] ?reference}.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY DESC (?date)
LIMIT 1000

Try it!

Thanks on advance for your help! --2le2im-bdc (talk) 19:57, 15 February 2021 (UTC)

@2le2im-bdc:
#Women dead in Paris before 1900 without reference for the date
SELECT ?item ?itemLabel ?date 
WHERE 
{
  ?item wdt:P21 wd:Q6581072 . # female
  ?item wdt:P20 / wdt:P131* wd:Q90 . # dead in Paris or a place located within Paris
  ?item p:P570 ?date_statement .
  ?date_statement a wikibase:BestRank . # With a date of death statement of best rank
  ?date_statement ps:P570 ?date .
  hint:Prior hint:rangeSafe true .
  FILTER (?date < "+1900-00-00T00:00:00Z"^^xsd:dateTime) # Dead before year 1900
  MINUS { ?item wdt:P31 wd:Q95074 . }
  MINUS { ?date_statement prov:wasDerivedFrom [] . } # No reference for the date of death statement
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" . }
}
ORDER BY DESC (?date)
LIMIT 1000
Try it! --Dipsacus fullonum (talk) 21:22, 15 February 2021 (UTC)
Thanks a lot @Dipsacus fullonum:! I have well done to ask : not so easy this query!--2le2im-bdc (talk) 14:30, 16 February 2021 (UTC)

Finding all organizations in a geographical area (how to fix a query)Edit

Hi folks! I previously had a search for all the cultural heritage organizations in a geographic area in Georgia, searching by county (see below). This query worked because I had (incorrectly) tagged all of the organizations with both their municipality and their county in the P131 field. The county values have since been removed from most of the organizations, leaving only the municipalities but not the county. My question is now, how do I change the below search to fix it so that it shows the organizations located in these counties, if we're not allowed to actually list the counties on the organizations' items?

SELECT DISTINCT ?organization ?organizationLabel ?street_address ?coordinate_location ?phone_number ?e_mail_address ?website ?Facebook_ID ?Twitter_username ?county WHERE {
  VALUES (?located_in_the_administrative_territorial_entity ?county) {
    (wd:Q486843 "Bleckley County")
    (wd:Q498301 "Pulaski County")
    (wd:Q486791 "Wilcox County")
    (wd:Q115272 "Dodge County")
    (wd:Q691614 "Telfair County")
    (wd:Q498332 "Wheeler County")
    (wd:Q493125 "Montgomery County")
    (wd:Q376822 "Toombs County")
    (wd:Q505310 "Tattnall County")
    (wd:Q111867 "Ben Hill County")
    (wd:Q492057 "Irwin County")
    (wd:Q156503 "Coffee County")
    (wd:Q493071 "Jeff Davis County")
    (wd:Q488186 "Appling County")
    (wd:Q488219 "Bacon County")
    (wd:Q488868 "Berrien County")
    (wd:Q488194 "Atkinson County")
    (wd:Q498353 "Ware County")
    (wd:Q492070 "Lanier County")
    (wd:Q493029 "Echols County")
    (wd:Q486167 "Clinch County")
  }
  VALUES ?instance_of {
    wd:Q473972
    wd:Q3152824
    wd:Q210272
    wd:Q570116
    wd:Q57660343
    wd:Q2668072
    wd:Q188913
    wd:Q15243209
    wd:Q2867476
    wd:Q635719
    wd:Q7840289
    wd:Q42998
    wd:Q41710
    wd:Q51369558
  }
  FILTER(NOT EXISTS { ?organization wdt:P576 _:b15. })
  ?organization (wdt:P31/(wdt:P279*)) ?instance_of;
    wdt:P131 ?located_in_the_administrative_territorial_entity.
  hint:Prior hint:runFirst "true"^^xsd:boolean.
  OPTIONAL { ?organization wdt:P6375 ?street_address. }
  OPTIONAL { ?organization wdt:P625 ?coordinate_location. }
  OPTIONAL { ?organization wdt:P1329 ?phone_number. }
  OPTIONAL { ?organization wdt:P968 ?e_mail_address. }
  OPTIONAL { ?organization wdt:P856 ?website. }
  OPTIONAL { ?organization wdt:P2013 ?Facebook_ID. }
  OPTIONAL { ?organization wdt:P2002 ?Twitter_username. }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
  OPTIONAL {  }
}
ORDER BY (?organization)
LIMIT 10000

Try it!

Any help is much appreciated! Clifflandis (talk) 20:27, 15 February 2021 (UTC)

@Clifflandis: The short answer is add "+" after wdt:P131 to make a property path of one or more instances of wdt:P131. The long answer is:
SELECT DISTINCT ?organization ?organizationLabel ?street_address ?coordinate_location
  ?phone_number ?e_mail_address ?website ?Facebook_ID ?Twitter_username ?county
WHERE {
  VALUES (?located_in_the_administrative_territorial_entity ?county) {
    (wd:Q486843 "Bleckley County")
    (wd:Q498301 "Pulaski County")
    (wd:Q486791 "Wilcox County")
    (wd:Q115272 "Dodge County")
    (wd:Q691614 "Telfair County")
    (wd:Q498332 "Wheeler County")
    (wd:Q493125 "Montgomery County")
    (wd:Q376822 "Toombs County")
    (wd:Q505310 "Tattnall County")
    (wd:Q111867 "Ben Hill County")
    (wd:Q492057 "Irwin County")
    (wd:Q156503 "Coffee County")
    (wd:Q493071 "Jeff Davis County")
    (wd:Q488186 "Appling County")
    (wd:Q488219 "Bacon County")
    (wd:Q488868 "Berrien County")
    (wd:Q488194 "Atkinson County")
    (wd:Q498353 "Ware County")
    (wd:Q492070 "Lanier County")
    (wd:Q493029 "Echols County")
    (wd:Q486167 "Clinch County")
  }
  VALUES ?instance_of {
    wd:Q473972
    wd:Q3152824
    wd:Q210272
    wd:Q570116
    wd:Q57660343
    wd:Q2668072
    wd:Q188913
    wd:Q15243209
    wd:Q2867476
    wd:Q635719
    wd:Q7840289
    wd:Q42998
    wd:Q41710
    wd:Q51369558
  }
  FILTER NOT EXISTS { ?organization wdt:P576 []. }
  ?organization wdt:P31/wdt:P279* ?instance_of.
  ?organization wdt:P131+ ?located_in_the_administrative_territorial_entity.
  OPTIONAL { ?organization wdt:P6375 ?street_address. }
  OPTIONAL { ?organization wdt:P625 ?coordinate_location. }
  OPTIONAL { ?organization wdt:P1329 ?phone_number. }
  OPTIONAL { ?organization wdt:P968 ?e_mail_address. }
  OPTIONAL { ?organization wdt:P856 ?website. }
  OPTIONAL { ?organization wdt:P2013 ?Facebook_ID. }
  OPTIONAL { ?organization wdt:P2002 ?Twitter_username. }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY (?organization)
LIMIT 10000
Try it! --Dipsacus fullonum (talk) 21:38, 15 February 2021 (UTC)
@Dipsacus fullonum: Thanks again for your help, but unfortunately it's giving me duplicates -- is there any way to fix this? For example, the second and third items that show up in the results are both for the Blue and Gray Museum (Q16843368) in Fitzgerald (Q654046), Georgia, USA. This is because the town of Fitzgerald exists in two counties, Ben Hill County (Q111867) and Irwin County (Q492057). So the search results display the Blue and Grey Museum twice, once for each county. Is there a way to de-duplicate the results list? I'll also ping @Mahir256: in case they may know how to help since they automated the removal of the county information from some of these organization's items. Again, thanks in advance for your help! Clifflandis (talk) 13:24, 16 February 2021 (UTC)
@Clifflandis: It isn't possible to find out which county institutions in Fitzgerald City is located in if more detailed information than the city isn't provided. It was proposed last year to make a hierarchy switch qualifier to indicate the county in cases like these. I see that you supported the proposal, but unfortunately it is still not concluded so it seems there is no recommended way to handle this at the moment. P131 could be used as a qualifier in the same way as the proposed "hierarchy switch", or there could be two independent statements with P131. I can make queries to handle both methods, but I cannot make queries to extract data that isn't provided. --Dipsacus fullonum (talk) 13:54, 16 February 2021 (UTC)
@Dipsacus fullonum: Okay, good to know -- I'll let the Federal Emergency Management Agency (Q503010) and Georgia Emergency Management and Homeland Security Agency (Q5547471) folks know that our queries will be broken until the community can reach a consensus on how to handle things like this.
Unfortunately, just adding a "+" after wdt:P131 is giving me a server error. Is there something else I need to change in the query to make it work? Again, thanks for your continued help! Clifflandis (talk) 14:14, 16 February 2021 (UTC)
@Dipsacus fullonum:, whoops! Nevermind, I see the additional edit's after "FILTER NOT EXISTS". Thanks again! Clifflandis (talk) 14:22, 16 February 2021 (UTC)
@Clifflandis: So very sorry for inadvertently making your work more difficult! (I was under the mistaken impression that this issue of multiple-county cities ended up being resolved.) When I went through and removed the P131 statements I removed, I was checking for statements that were both of normal rank, which both lacked qualifiers, and where one value was wdt:P131/wdt:P131* the other value (which, it turns out, most of the Georgia items' statements satisfied). Seeing now that this also removed statements where the extra county value was actually useful, I used the query below to find places located in cities/towns in multiple Georgia counties and restored the county statements I removed (while adding a qualifier to them so that I don't touch them again later):
SELECT DISTINCT ?i ?iLabel
WITH {
  SELECT ?c ?cLabel {
    ?c wdt:P131 ?a; wdt:P131 ?b.
    wd:Q13410428 ^wdt:P31 ?a, ?b.
    wd:Q1428 ^wdt:P131 ?a, ?b.
    FILTER(STR(?a) < STR(?b))
  }
} AS %cs
WHERE {
  INCLUDE %cs.
  ?i wdt:P131/wdt:P131* ?c.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Try it!
If there's anything I missed (which still shows up as duplicates in your original query, for instance), please let me know. Sorry for the trouble again! Mahir256 (talk) 15:53, 16 February 2021 (UTC)
@Mahir256: thanks for restoring the counties with the new next level in hierarchy (Q105528942) qualifier. Right now, when I search using the search above that Dipsacus fullonum modified for me, it's still showing duplicate instances for any organization that is in a city with more than one county. Do you know how to modify the search based around the new qualifier, so that excludes those duplicate records with the incorrect county? For example, the search above is still showing the Blue and Gray Museum (Q16843368) twice -- is there a way to only show the single entry with the correct county (Ben Hill County (Q111867)? Thanks in advance for your help! Clifflandis (talk) 17:40, 16 February 2021 (UTC)
@Dipsacus fullonum: Is there a way to modify the query to only show the correct county, if the P131 field includes both the municipality and county (based around the county's qualifier of object has role (P3831) next level in hierarchy (Q105528942))? For example, Blue and Gray Museum (Q16843368). Right now it's showing up twice in search results based around Fitzgerald being in two counties (once for each county). I'm just not sure how the search logic should go if the query is using the typical P131 hierarchy for 1-to-1 city-to-county items (using wdt:P131+), but then have the query switch for 1-to-many items to only display the correct county if the county is declared in the item... I hope that makes sense. As always, thanks in advance for your help! Clifflandis (talk) 13:28, 17 February 2021 (UTC)
@Clifflandis: It is possible but the data model using object has role (P3831) next level in hierarchy (Q105528942) as introduced by Mahir256 isn't easy to query and gives rather complicated queries. I found this solution after much work and experimentation:
SELECT DISTINCT ?organization ?organizationLabel ?street_address ?coordinate_location
  ?phone_number ?e_mail_address ?website ?Facebook_ID ?Twitter_username ?county
WITH
{
  SELECT DISTINCT ?organization ?located_in_the_administrative_territorial_entity ?county
  WHERE
  {
    hint:Query hint:optimizer "None".
    VALUES (?located_in_the_administrative_territorial_entity ?county) {
      (wd:Q486843 "Bleckley County")
      (wd:Q498301 "Pulaski County")
      (wd:Q486791 "Wilcox County")
      (wd:Q115272 "Dodge County")
      (wd:Q691614 "Telfair County")
      (wd:Q498332 "Wheeler County")
      (wd:Q493125 "Montgomery County")
      (wd:Q376822 "Toombs County")
      (wd:Q505310 "Tattnall County")
      (wd:Q111867 "Ben Hill County")
      (wd:Q492057 "Irwin County")
      (wd:Q156503 "Coffee County")
      (wd:Q493071 "Jeff Davis County")
      (wd:Q488186 "Appling County")
      (wd:Q488219 "Bacon County")
      (wd:Q488868 "Berrien County")
      (wd:Q488194 "Atkinson County")
      (wd:Q498353 "Ware County")
      (wd:Q492070 "Lanier County")
      (wd:Q493029 "Echols County")
      (wd:Q486167 "Clinch County")
    }
    ?organization wdt:P131+ ?located_in_the_administrative_territorial_entity .
    FILTER NOT EXISTS { ?organization wdt:P576 [] . }
    VALUES ?instance_of {
      wd:Q473972
      wd:Q3152824
      wd:Q210272
      wd:Q570116
      wd:Q57660343
      wd:Q2668072
      wd:Q188913
      wd:Q15243209
      wd:Q2867476
      wd:Q635719
      wd:Q7840289
      wd:Q42998
      wd:Q41710
      wd:Q51369558
    }
    ?organization wdt:P31/wdt:P279* ?instance_of .
    hint:Prior hint:gearing "forward" .
  }
}
AS %get_organization_and_county_candidates
WITH
{
  SELECT ?organization ?located_in_the_administrative_territorial_entity ?county
  WHERE
  {
    INCLUDE %get_organization_and_county_candidates
    # The administrative unit (here county) is mentioned directly in the organization item
    FILTER EXISTS { ?organization wdt:P131 ?located_in_the_administrative_territorial_entity . }
  }
}
AS %organizations_with_county_statement
WITH
{
  SELECT ?organization ?located_in_the_administrative_territorial_entity ?county
  WHERE
  {
    INCLUDE %get_organization_and_county_candidates
    # The administrative unit (here county) is deeper in the P131 hierarchy
    # AND there is no "next level in hierarchy" qualifier in another P131 statement  
    FILTER EXISTS
    {
      ?organization p:P131 ?P131_statement .
      ?P131_statement ps:P131 ?first_level_adm_unit .
      ?first_level_adm_unit wdt:P131+ ?located_in_the_administrative_territorial_entity .
      FILTER NOT EXISTS
      {
        ?organization p:P131 ?another_P131_statement .
        FILTER (?another_P131_statement != ?P131_statement)
        ?another_P131_statement pq:P3831 wd:Q105528942 .
      }
    }
  }
}
AS %organizations_without_county_statement
WHERE
{
  { INCLUDE %organizations_with_county_statement }
  UNION
  { INCLUDE %organizations_without_county_statement }
  OPTIONAL { ?organization wdt:P6375 ?street_address . }
  OPTIONAL { ?organization wdt:P625 ?coordinate_location . }
  OPTIONAL { ?organization wdt:P1329 ?phone_number . }
  OPTIONAL { ?organization wdt:P968 ?e_mail_address . }
  OPTIONAL { ?organization wdt:P856 ?website . }
  OPTIONAL { ?organization wdt:P2013 ?Facebook_ID . }
  OPTIONAL { ?organization wdt:P2002 ?Twitter_username . }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . }
}
ORDER BY (?organization)
Try it! --Dipsacus fullonum (talk) 13:51, 22 February 2021 (UTC)
@Dipsacus fullonum: Thanks for your help with this! I know it's a pain trying to work around the transitive property limitations of P131. I'm going to try rewriting the 168 queries we have for Georgia with this pattern, and hopefully everything will work. I'm a little concerned that this way of doing things makes the queries more likely to break over time, but since listing both the municipality and county at the same time in the P131 is against the rules, my hands are kind of tied. Regardless, thanks again for your tireless help!!! Clifflandis (talk) 20:29, 23 February 2021 (UTC)
@Clifflandis: That's many query to rewrite. I am sorry to say it, but I hope that they will break over time as I don't think the use of object has role (P3831) next level in hierarchy (Q105528942) is a good solution. The queries would be simpler and easier with a new qualifier to indicate the next level of hierarchy. The query is so complicated now because the info is spread over two statements. One statement with a qualifier would be easier to handle. --Dipsacus fullonum (talk) 23:42, 23 February 2021 (UTC)
@Dipsacus fullonum: Okay, if this is a bad/inelegant solution, we should come up with a better one. We tried to get this problem addressed before through discussion, with no luck (please see 1, 2, 3, 4). Maybe @Mahir256: can help since they're an admin. Mahir256, what do you recommend we do next to address this technical problem? Clifflandis (talk) 14:29, 24 February 2021 (UTC)
The problem is that the layers are not strictly hierarchical. So adding several parallel ones (county and city) to an item is fine.
I do find the part with the strings in the query odd though (county names). Why aren't these queried? --- Jura 16:02, 24 February 2021 (UTC)
Jura wrote: "So adding several parallel ones (county and city) to an item is fine." No, it is not fine. When you have Blue and Gray Museum (Q16843368) located in the administrative territorial entity (P131) Fitzgerald (Q654046) with no qualifiers to alter the statement and Fitzgerald (Q654046) located in the administrative territorial entity (P131) Irwin County (Q492057) again with no qualifiers, you should be able to conclude that Blue and Gray Museum (Q16843368) also is in Irwin County (Q492057) which isn't the case. That information can be derived from a qualifier in another statement – but qualifiers should only the alter statement where they are placed and not other statements. Two different statements should be independent so one statement's qualifier doesn't affect how another statement should be interpreted. So this data model besides making queries difficult to construct, also is wrong from a data representation viewpoint. --Dipsacus fullonum (talk) 16:27, 24 February 2021 (UTC)
The problem in Georgia is that one city can be in several counties. So places are located in one city and a county different from another place in the same city. --- Jura 17:11, 24 February 2021 (UTC)

All articles of a specific Wikipedia with their QIDs and current sitelinksEdit

Hello everyone, I want a query to obtain all articles (no redirect pages) of ckbwiki with their QID and current sitelinks. Thanks, Aram (talk) 19:49, 16 February 2021 (UTC)

@Aram: : something like this ? I don’t know if the redirects are correctly handled. It’s suppose to use the redirect badges but I don’t know if this is up to date yet.

select distinct ?item ?article ?name {
 ?article schema:isPartOf <https://ckb.wikipedia.org/> ; schema:about ?item ; schema:name ?name 
 minus {
 ?article schema:isPartOf <https://ckb.wikipedia.org/> ; wikibase:badge ?badge   .
          values ?badge { wd:Q70893996 wd:Q70894304} 
 }
}

Try it! author  TomT0m / talk page 17:19, 20 February 2021 (UTC)

@TomT0m: Thank you for your great help! I think it excludes the redirect pages to articles successfully, but the query retrieves other namespaces such as category and template namespaces. Can you make it exclude all namespaces (except articles)? Thank you again! Aram (talk) 18:39, 20 February 2021 (UTC)
Template:Pinq you are right. The namespace is not easily available in Wikidata, so instead I did this with a quarry querry. This should be more reliable and straightforward, and also catches the articles without items. If the querry is not wrong, this is my first quarry query - could you please double check with the known number of articles in this wiki ? author  TomT0m / talk page 20:55, 20 February 2021 (UTC)
@TomT0m: That's great! I just want another column for article sitelinks. Would be? Aram (talk) 20:57, 21 February 2021 (UTC)
@Aram: What do you mean "sitelinks" ? Do you want all articles titles in all wikis corresponding to those articles ? A link to ckbwiki url for the article ? The uris does not seem to actually be stored by the database tables, so if you want this it has to be retrieved from the sparql wikibase endpoint. author  TomT0m / talk page 12:32, 22 February 2021 (UTC)
@TomT0m: Oh, I'm sorry! I want to update all ckbwiki article labels on wikidata. And according to here, I just want the QIDs and the article names. Well done! We'll appreciate it! And Thank you very much! Aram (talk) 13:23, 22 February 2021 (UTC)

Wikipedia articles with identifier here but no authority control template thereEdit

Here’s my attempt at a query to get everything with Internet Encyclopedia of Ukraine ID (P9070) and subtract everything in w:en: Category:Wikipedia articles with IEU identifiers. Some bits are cobbled from examples, but I don’t know how the FILTER BOUND and contents of the MINUS parts work. This times out. Thanks for any advice. —Michael Z. 16:22, 18 February 2021 (UTC)

# Items with Internet Encyclopedia of Ukraine ID but no IEU identifier in en.Wikipedia

SELECT DISTINCT ?item ?itemLabel ?itemDescription ?IEU_link ?enarticle WHERE {
  
  BIND('en' AS ?lang).
  BIND(CONCAT(?lang, '.wikipedia.org') AS ?project).
  
  ?item wdt:P9070 ?IEU_ID . # item’s IEU ID
  wd:P9070 wdt:P1630 ?formatterurl . # get its formatter
  
  ?enarticle schema:about ?item ; 
             schema:inLanguage ?lang ; 
             schema:isPartOf <https://en.wikipedia.org/> ; 
             schema:name ?enname .

  FILTER BOUND(?enarticle) # Safeguard to not get a timeout from unbound items when using ?enarticle below

  MINUS {    
    # en.Wikipedia articles in Category:Wikipedia articles with IEU identifiers
    SERVICE wikibase:mwapi {
      bd:serviceParam wikibase:endpoint ?project;     # Set the project here
                      wikibase:api "Generator";
                      mwapi:generator "categorymembers";        # Selects the content from a category
                      mwapi:gcmtitle "Category:Wikipedia articles with IEU identifiers";.    # Specifies the category
      ?enarticle wikibase:apiOutputItem mwapi:item.
    }
  } 
  
  # derive the IEU URL
  BIND(IRI(REPLACE( 
    REPLACE(?IEU_ID, '\\', '%5C', 'q'), # percent-encode backslash
    '^(.+)$', 
    REPLACE(?formatterurl, '\\', '%5C', 'q') # percent-encode backslash
  )) AS ?IEU_link) .
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en,en"  }
  
}

Try it!

@Mzajac: This seems to work. In your query, what emerges from the MWAPI service is not ?enarticle but ?item. Beyond that, quite why minus was not behaving is beyond me. So I've more struck upon the below as a solution, than arrived at it by deep understanding of SPARQL.
# Items with Internet Encyclopedia of Ukraine ID but no IEU identifier in en.Wikipedia
SELECT DISTINCT ?item ?itemLabel ?itemDescription ?IEU_link ?enarticle  with { select ?item ?IEU_link ?enarticle WHERE {
  BIND('en' AS ?lang).
  BIND(CONCAT(?lang, '.wikipedia.org') AS ?project).
  ?item wdt:P9070 ?IEU_ID . # item’s IEU ID
  wd:P9070 wdt:P1630 ?formatterurl . # get its formatter
  ?enarticle schema:about ?item ; 
             schema:inLanguage ?lang ; 
             schema:isPartOf <https://en.wikipedia.org/> ; 
             schema:name ?enname .
  # derive the IEU URL
  BIND(IRI(REPLACE( 
    REPLACE(?IEU_ID, '\\', '%5C', 'q'), # percent-encode backslash
    '^(.+)$', 
    REPLACE(?formatterurl, '\\', '%5C', 'q') # percent-encode backslash
  )) AS ?IEU_link) .  
} } as %i
where
{
  include %i
  filter not exists  {select ?item where {    
    # en.Wikipedia articles in Category:Wikipedia articles with IEU identifiers
    SERVICE wikibase:mwapi {
     bd:serviceParam wikibase:endpoint "en.wikipedia.org";
                     wikibase:api "Generator";
                     mwapi:generator "categorymembers";
                     mwapi:gcmtitle "Category:Wikipedia articles with IEU identifiers" ;
                     mwapi:gcmprop "ids|title|type";
                     mwapi:gcmlimit "max".
     # out
     ?item wikibase:apiOutputItem mwapi:item.
    }
 } }
  FILTER BOUND(?item) # Safeguard to not get a timeout from unbound items 
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en"  }
  }
Try it! --Tagishsimon (talk) 03:16, 19 February 2021 (UTC)
Thank you! I’d never have managed that. —Michael Z. 14:35, 19 February 2021 (UTC)
@Mzajac: Au contrete. As you can do the query you did, you can do the query I did. Have you met the query optimization page? --Tagishsimon (talk) 14:56, 19 February 2021 (UTC)

Query for events on days or array of yearsEdit

Hello,

 I'm trying to do an historical research and I'd like to create a query searching for events happened on a specific date (like the "#All events that occured on 2001/09/11" query, that is fine), but also events happened on a specific day regardless the year, or in the same date but within a set of specified years.

I've tried to "merge" the "#All events that occured on 2001/09/11" query with the "#Eventi recenti" one, but with no luck: my knowledge of SPARQL is absolutely zero.

Hints?


Thank you

165.225.202.193 08:08, 19 February 2021 (UTC)Marco

Basically, something like that
#All events that occured on 09/11 any year
SELECT ?item ?itemLabel 
WHERE
{
  ?item  wdt:P585 ?date .
  filter (day(?date) = 9) filter (month(?date) = 11)
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Try it!
A bit rough probably, you may want to remove all days themselves, each day has its item and it’s not very interesting, and there is way more ways to add dates on events than just use the date property on an item. But surprisingly it does not timeouts. author  TomT0m / talk page 09:17, 19 February 2021 (UTC)


Seems nice though. Thank you. I'll try to manage the results.

165.225.202.193 09:32, 19 February 2021 (UTC)Marco

Women and LGBTQ+ Cartoonists with Stub, Start, or C Class Articles on English WikipediaEdit

Hello. I'm requesting a query of articles about women and LGBTQ+ cartoonists rated stub, start, or C class on English Wikipedia. Thank you. - clickhere21 (talk) 22:37, 19 February 2021 (UTC)

For a start, a complete list
select ?item ?itemLabel ?genreLabel ?article ?badge ?badgeLabel {
  ?item wdt:P31 wd:Q5 ;
        wdt:P106/wdt:P279* wd:Q266569 .
  optional {
    ?item wdt:P21 ?genre
  }
  filter (?genre != wd:Q6581097 ).
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  optional {
    ?article schema:about ?item ; schema:isPartOf <https://en.wikipedia.org/> .
            optional {?article  wikibase:badge ?badge }
             
  }
}
Try it! with the persons without an article on enwiki included, and the one with unknown/without gender on Wikidata. author  TomT0m / talk page 15:35, 20 February 2021 (UTC)
Combining with article rate is less easy to do, at least I don’t know how automatically : the categories are on the talk pages, and tools like Petscan could not deal with that last time I checked. author  TomT0m / talk page 15:48, 20 February 2021 (UTC)

@clickhere21: I think I managed to find something that works using mwapi though :

select distinct ?item ?itemLabel ?genreLabel ?article ?name (lang(?name) as ?lang) ?category {
  ?item wdt:P31 wd:Q5 ;
        wdt:P106/wdt:P279* wd:Q266569 .
  optional {
    ?item wdt:P21 ?genre
  }
  filter (?genre != wd:Q6581097 ).
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  ?article schema:about ?item ; schema:isPartOf <https://en.wikipedia.org/> ; schema:name ?name


  ########### find articles by their ratings on enwiki

  # compute the name of the talk page on enwiki
  bind (concat("Talk:", ?name) as ?title)

  # find the categories of the talkpage using mwapi
  SERVICE wikibase:mwapi {
      # Categories that contain these pages
     bd:serviceParam wikibase:api "Categories";
                      wikibase:endpoint "en.wikipedia.org";
                      mwapi:titles  ?title.
       # Output the page title and category
      #?otitle wikibase:apiOutput mwapi:title.
      ?category wikibase:apiOutput mwapi:category .  
  }
  values ?category { #### add relevant (sub?)categories if needed 
    "Category:Start-Class biography articles" 
    "Category:Stub-Class biography articles"
    "Category:C-Class biography articles"
  }
}
Try it!

It might not work if some biographies are in subcategories of "Category:Start-Class biography articles" or the like, however. If it’s needed, there is a solution to this problem #Return all subcategories from a category in a request above, so please ask. author  TomT0m / talk page 16:51, 20 February 2021 (UTC)

Sweet. --Tagishsimon (talk) 17:32, 20 February 2021 (UTC)
A second version to avoid the « distinct »
select ?item ?itemLabel ?genreLabel ?article ?name (lang(?name) as ?lang) ?category {
  ?item wdt:P31 wd:Q5 ;
        wdt:P106/wdt:P279* wd:Q266569 .
  optional {
    ?item wdt:P21 ?genre
  }
  filter (?genre != wd:Q6581097 ).
  
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  ?article schema:about ?item ; schema:isPartOf <https://en.wikipedia.org/> ; schema:name ?name


  ########### find articles by their ratings on enwiki

  # compute the name of the talk page on enwiki
  bind (concat("Talk:", ?name) as ?title)

  # find the categories of the talkpage using mwapi
  SERVICE wikibase:mwapi {
      # Categories that contain these pages
     bd:serviceParam wikibase:api "Categories";
                      wikibase:endpoint "en.wikipedia.org";
                      mwapi:titles  ?title.
       # Output the page title and category
      ?ocategory wikibase:apiOutput mwapi:category .  
  }
  values ?category { #### add relevant (sub?)categories if needed 
    "Category:Start-Class biography articles" 
    "Category:Stub-Class biography articles"
    "Category:C-Class biography articles"
  } filter (?category = ?ocategory)
}
Try it! author  TomT0m / talk page 11:39, 22 February 2021 (UTC)

Wikimedia Commons Query ServiceEdit

c:File:MA I317916 TePapa Diplodontias-robustus full.jpg depicts (P180) NMNZ EC.000109 (Q105585285)
  • and showing only the items are coming from a specific collection, exemple:
NMNZ EC.000109 (Q105585285) collection (P195) Museum of New Zealand Te Papa Tongarewa (Q915603)
  • and if possible givin the values of the following property and qualifier:
NMNZ EC.000109 (Q105585285) subject has role (P2868) **** of (P642) ****

Christian Ferrer (talk) 15:18, 21 February 2021 (UTC)

@Christian Ferrer: There are 10 items in WDQS which meet your conditions, but currently no images in WCQS which depicts these items. This query finds the items and would show the files if there were any. I see that you edited the structured data for c:File:MA I317916 TePapa Diplodontias-robustus full.jpg two days ago, so it should be in the results after the next weekly update of WCQS.
SELECT ?file ?item ?itemLabel ?role ?roleLabel ?for ?forLabel
WITH
{
  # Get items for type specimens at Museum of New Zealand Te Papa Tongarewa from WDQS
  SELECT ?item ?itemLabel ?role ?roleLabel ?for ?forLabel
  WHERE
  {
    SERVICE <https://query.wikidata.org/sparql>
    {
      ?item wdt:P31 wd:Q51255340 . # Item is a type specimen
      ?item wdt:P195 wd:Q915603 . # Collection is Museum of New Zealand Te Papa Tongarewa
      OPTIONAL
      {
        ?item p:P2868 ?stat .
        ?stat ps:P2868 ?role .
        ?stat pq:P642 ?for .
      }
      SERVICE wikibase:label
      {
        bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" .
        ?item rdfs:label ?itemLabel .
        ?role rdfs:label ?roleLabel .
        ?for rdfs:label ?forLabel .
      }
    }
  }
}
AS %get_items
{
  INCLUDE %get_items
  OPTIONAL { ?file wdt:P180 ?item . }
}
Try it! --Dipsacus fullonum (talk) 17:12, 21 February 2021 (UTC)
My version, all results but decomment the « values » section to include only one or several specific collections
#defaultView:ImageGrid

SELECT ?file ?image ?stype ?stypeLabel ?collec ?collecLabel ?role ?roleLabel ?de ?deLabel
with {
  select ?stype ?stypeLabel ?collec ?collecLabel ?role ?de ?roleLabel ?deLabel {
   service <https://query.wikidata.org/sparql> {
     select ?stype ?stypeLabel ?collec ?collecLabel ?role ?de ?roleLabel ?deLabel { 
       ?stype wdt:P31/wdt:P279* wd:Q51255340 
       SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
       optional {
         ?stype wdt:P195 ?collec .
       }
       optional {
         ?stype p:P2868 [ps:P2868 ?role ; pq:P642 ?de]
       }
       #enlevez les # au dessous pour préciser une ou des collections
       #values ?collec {
       # wd:Q122945 # exemple avec le Yale Peabody Museum of Natural History 
       #}
     }
   }
  }
} as %types
WHERE {
  ?file wdt:P180 ?stype ; schema:contentUrl ?url .
  
  bind(iri(concat("http://commons.wikimedia.org/wiki/Special:FilePath/", replace(substr(str(?url),53),"_","%20"))) AS ?image) .
  
  #?file wdt:P180  wd:Q105607273  .
  include %types
}
Try it!
  • @Dipsacus fullonum: hi, thanks you. The second query you give don't show results, and I'm not able to undesrtand it. For the first I did not know that there is a delay, so with a different collection we can get some resuls. However is there a way to display a gallery instead of a table? Christian Ferrer (talk) 17:45, 21 February 2021 (UTC)
    • @Christian Ferrer: Check mine, it did not work because I did forget to use the right endpoint in the template, but it should be OK now. author  TomT0m / talk page 17:50, 21 February 2021 (UTC)
@Christian Ferrer: See c:Commons:SPARQL query service for the delay. I qoute: "The service is a beta endpoint that is updated via weekly dumps. ... The data will be reloaded weekly on Mondays from dumps taken on Sunday." --Dipsacus fullonum (talk) 18:05, 21 February 2021 (UTC)
PS. I can add that I didn't use an image grid because there were no images anyway for the selected collection. --Dipsacus fullonum (talk) 18:14, 21 February 2021 (UTC)
  • @TomT0m: is it possible also to filter the type specimens of a specific taxon and of his child taxa? e.g. all the images depicting items of types specimens of Brachypoda (Q15711568) (and of its children). The relation parent/child is done with parent taxon (P171), so I guess it is with a thing like that:wdt:P171/wdt:P171* wd:Q15711568 Christian Ferrer (talk) 18:35, 21 February 2021 (UTC)
    Sure @Christian Ferrer:, you’re almost right the line should be ?de wdt:P171* wd:Q15711568 as you want to keep the parent taxon (your one selected only its children, not the parent itself):
    #defaultView:ImageGrid
    
    SELECT ?file ?image ?stype ?stypeLabel ?collec ?collecLabel ?role ?roleLabel ?de ?deLabel
    with {
      select ?stype ?stypeLabel ?collec ?collecLabel ?role ?de ?roleLabel ?deLabel {
       service <https://query.wikidata.org/sparql> {
         select ?stype ?stypeLabel ?collec ?collecLabel ?role ?de ?roleLabel ?deLabel { 
           ?stype wdt:P31/wdt:P279* wd:Q51255340 
           SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
           optional {
             ?stype wdt:P195 ?collec .
           }
           ?stype p:P2868 [ps:P2868 ?role ; pq:P642 ?de] .
           #enlevez les # au dessous pour préciser une ou des collections
           #values ?collec {
           # wd:Q122945 # exemple avec le Yale Peabody Museum of Natural History 
           #}
           ?de wdt:P171* wd:Q15711568 . # choisir un taxon dont on cherche les types, incluant les types de ses sous-taxons
         }
       }
      }
    } as %types
    WHERE {
      ?file wdt:P180 ?stype ; schema:contentUrl ?url .
      
      bind(iri(concat("http://commons.wikimedia.org/wiki/Special:FilePath/", replace(substr(str(?url),53),"_","%20"))) AS ?image) .
      
      #?file wdt:P180  wd:Q105607273  .
      include %types
    }
    
    Try it! author  TomT0m / talk page 11:21, 22 February 2021 (UTC)
  • @TomT0m: thanks, but it seems there is something wrong as there is no result, I chose that taxon because we should have at least two results c:File:Hutchinsoniella macracantha (YPM IZ 003617.CR) 002.jpeg and c:File:Hutchinsoniella macracantha (YPM IZ 003617.CR) 001.jpeg. Christian Ferrer (talk) 11:42, 22 February 2021 (UTC)
    (I’ll learn at some point) Problem in the template call, wrong sparql endpoint :) should be OK now @Christian Ferrer: author  TomT0m / talk page 11:44, 22 February 2021 (UTC)
  • @TomT0m: Excellent, thanks you. Structured data for Commons has a great potential(and Wikidata in general), it is likely one of the most powerfull toll available to the public in the WEB, if not the most powerfull tool, to sort and find images. It lacks only the data on the files, and the imagination of those who make the requests will do the rest . Christian Ferrer (talk) 11:53, 22 February 2021 (UTC)

Match a string in the descriptionEdit

I haven't been able to find an example query that does this. I want to find all instances of human that have "recusant" in the description. Can we do this? - PKM (talk) 21:49, 22 February 2021 (UTC)

Search for "haswbstatement:P31=Q5 recusant". You can use the normal search special page (https://www.wikidata.org/w/index.php?search=haswbstatement%3AP31%3DQ5+recusant&title=Special%3ASearch&ns0=1) or make a SPARQL query with a MWAPI call to do the search.
@PKM: I forgot my signature above. There is an example of MWAPI search at Wikidata:SPARQL query service/query optimization#Searching labels. Just change the search string to haswbstatement:P31=Q5 recusant and replace rdfs:label in the example with schema:description to search for descriptions instead of labels. --Dipsacus fullonum (talk) 22:30, 22 February 2021 (UTC)
@Dipsacus fullonum: perfect, thanks! - PKM (talk) 22:33, 22 February 2021 (UTC)

QuestionEdit

Hi,
I don't know why I have 126 results in the first query and 33 in the second for (wdt:P1037|wdt:P169|wdt:P8938) ?direction. Someone can explain this to me? I try to get all the direction entries and know the percentages of them who are male and female. Simon Villeneuve (talk) 14:51, 23 February 2021 (UTC)

SELECT ?item ?itemLabel ?directionLabel ?direction
WHERE 
{
  ?item ?ppp ?statement . 
   ?property a wikibase:Property ;
     wikibase:claim ?ppp . 
  
  ?statement ?qqq ?value.
   ?property2 a wikibase:Property ;
     wikibase:statementProperty  ?qqq . 
  
  ?statement prov:wasDerivedFrom ?autre_statement. #d'après la source ...
  ?autre_statement pr:P248 wd:Q100443909 .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    ?item wdt:P31 / wdt:P279* wd:Q43229 ;
          (wdt:P1037|wdt:P169|wdt:P8938) ?direction .
}

Try it!

#Tous les éléments distincts sourcés avec le CQT avec les pourcentages de certaines natures, pays, naissance, etc..

SELECT (COUNT(DISTINCT ?item) AS ?total)
  (COUNT(DISTINCT ?membre_CQT) AS ?est_membre_CQT) (?est_membre_CQT / ?total * 100.0 AS ?pct_membre_CQT)
  (COUNT(DISTINCT ?item_a_pays) AS ?a_pays) (?a_pays / ?total * 100.0 AS ?pct_pays)
  (COUNT(DISTINCT ?item_a_image) AS ?a_image) (?a_image / ?total * 100.0 AS ?pct_image)
  (COUNT(DISTINCT ?item_est_géolocalisé) AS ?est_géolocalisé) (?est_géolocalisé / ?total * 100.0 AS ?pct_géolocalisé)
  (COUNT(DISTINCT ?item_est_organisation) AS ?est_organisation) (?est_organisation / ?total * 100.0 AS ?pct_organisation)
  (COUNT(?organisation_a_direction) AS ?a_direction) (?a_direction / ?est_organisation * 100.0 AS ?pct_direction)
  (COUNT(DISTINCT ?directionféminin) AS ?direction_féminin) (?direction_féminin / ?a_direction * 100.0 AS ?pct_direction_féminin)
  (COUNT(DISTINCT ?directionmasculin) AS ?direction_masculin) (?direction_masculin / ?a_direction * 100.0 AS ?pct_direction_masculin)
  (COUNT(DISTINCT ?item_est_oeuvre) AS ?est_oeuvre) (?est_oeuvre / ?total * 100.0 AS ?pct_oeuvre)
  (COUNT(?item_est_humain) AS ?est_humain) (?est_humain / ?total * 100.0 AS ?pct_humain)
  (COUNT(?item_est_féminin) AS ?est_féminin) (?est_féminin / ?est_humain * 100.0 AS ?pct_féminin)
  (COUNT(?item_est_masculin) AS ?est_masculin) (?est_masculin / ?est_humain * 100.0 AS ?pct_masculin)
  (COUNT(?item_est_nonsexué) AS ?est_nonsexué) (?est_nonsexué / ?est_humain * 100.0 AS ?pct_nonsexué) #non précisé
  (COUNT(DISTINCT ?item_a_naissance) AS ?a_naissance) (?a_naissance / ?est_humain * 100.0 AS ?pct_naissance)
  (COUNT(DISTINCT ?item_a_mort) AS ?est_mort) (?est_mort / ?est_humain * 100.0 AS ?pct_mort)
  (COUNT(DISTINCT ?date_décennie) AS ?a_décennie) (?a_décennie / ?est_humain * 100.0 AS ?pct_décennie)
  (COUNT(DISTINCT ?occupation) AS ?a_occupation) (?a_occupation / ?est_humain * 100.0 AS ?pct_occupation)
  (COUNT(DISTINCT ?fonction) AS ?a_fonction) (?a_fonction / ?est_humain * 100.0 AS ?pct_fonction)
  (COUNT(DISTINCT ?item_a_langueoeuvre) AS ?a_langueoeuvre) (?a_langueoeuvre / ?est_oeuvre * 100.0 AS ?pct_langue)
  (COUNT(DISTINCT ?oeuvre_est_fr) AS ?est_fr) (?est_fr / ?est_oeuvre * 100.0 AS ?pct_fr)
  (COUNT(DISTINCT ?oeuvre_est_en) AS ?est_en) (?est_en / ?est_oeuvre * 100.0 AS ?pct_en)
WITH
{
  SELECT DISTINCT ?item
  WHERE
  {
    # Trouver les éléments avec le CQT en référence
    ?autre_statement pr:P248 wd:Q100443909 .
    ?statement prov:wasDerivedFrom ?autre_statement .

    # Quelles propriétés sont sourcées par le CQT
    ?property a wikibase:Property ;
       wikibase:claim ?ppp .
    ?item ?ppp ?statement .
  }
}
AS %items_CQT
WHERE
{
  INCLUDE %items_CQT
  OPTIONAL
  {
    ?item wdt:P463 wd:Q64402570 .
    BIND (?item AS ?membre_CQT)
  }
  OPTIONAL
  {
    ?item (wdt:P17 | wdt:P27) ?pays .
    BIND (?item AS ?item_a_pays)
  }
  OPTIONAL
  {
    ?item wdt:P18 ?image .
    BIND (?item AS ?item_a_image)
  }
  OPTIONAL
  {
    ?item wdt:P625 ?géolocalisé .
    BIND (?item AS ?item_est_géolocalisé)
  }
  OPTIONAL
  {
    ?item wdt:P31 / wdt:P279* wd:Q43229 .
    hint:Prior hint:gearing "forward" .
    BIND (?item AS ?item_est_organisation)
  }
    OPTIONAL
  {
    ?item wdt:P31 / wdt:P279* wd:Q43229 ;
          (wdt:P1037|wdt:P169|wdt:P8938) ?direction .
    BIND (?item AS ?organisation_a_direction)
  }
    OPTIONAL
  {
    ?item wdt:P31 / wdt:P279* wd:Q43229 ;
          (wdt:P1037|wdt:P169|wdt:P8938) ?direction .
    ?direction wdt:P21 wd:Q6581072 .
    BIND (?item AS ?directionféminin)
  }
    OPTIONAL
  {
    ?item wdt:P31 / wdt:P279* wd:Q43229 ;
          (wdt:P1037|wdt:P169|wdt:P8938) ?direction .
    ?direction wdt:P21 wd:Q6581097 .
    BIND (?item AS ?directionmasculin)
  }
    OPTIONAL
  {
    ?item wdt:P31 / wdt:P279* wd:Q386724 .
    hint:Prior hint:gearing "forward" .
    BIND (?item AS ?item_est_oeuvre)
  }
  OPTIONAL
  {
    ?item wdt:P31 wd:Q5 .
    BIND (true AS ?item_est_humain)
  }
  OPTIONAL
  {
    ?item wdt:P31 wd:Q5.
    minus {?item wdt:P21 ?sexe .}
    BIND (true AS ?item_est_nonsexué)
  }
  OPTIONAL
  {
    ?item wdt:P21 wd:Q6581072 .
    BIND (true AS ?item_est_féminin)
  }
  OPTIONAL
  {
    ?item wdt:P21 wd:Q6581097 .
    BIND (true AS ?item_est_masculin)
  }
  OPTIONAL
  {
    ?item wdt:P569 ?naissance .
    BIND (?item AS ?item_a_naissance)
  }
  OPTIONAL
  {
    ?item wdt:P570 ?mort .
    BIND (?item AS ?item_a_mort)
  }
  OPTIONAL
  {
    ?item (p:P569/psv:P569|p:P570/psv:P570) [wikibase:timePrecision ?datePrecision; wikibase:timeValue ?naissance ] .
  filter(?datePrecision=8)
    BIND (?item AS ?date_décennie)
  }
  OPTIONAL
  {
    ?item wdt:P106 ?occupation .
    BIND (?item AS ?item_a_occupation)
  }
  OPTIONAL
  {
    ?item wdt:P39 ?fonction .
    BIND (?item AS ?item_a_fonction)
  }
   OPTIONAL
  {
    ?item wdt:P407 ?langueoeuvre .
    BIND (?item AS ?item_a_langueoeuvre)
  }
    OPTIONAL
  {
    ?item wdt:P407 wd:Q150 .
    BIND (?item AS ?oeuvre_est_fr)
  }
      OPTIONAL
  {
    ?item wdt:P407 wd:Q1860 .
    BIND (?item AS ?oeuvre_est_en)
  }
}

Try it!

Note that while the first query do have 126 results, there are only 11 distinct results. There are many duplicate results because the (few) found items each have many statements with CQT used as reference. --Dipsacus fullonum (talk) 16:36, 23 February 2021 (UTC)
Thank you for your answer. I knew there was undistinct results. I thought that without DISTINCT, the 2 queries will give me the same number of undistincts results, but it's not the case. Simon Villeneuve (talk) 14:20, 24 February 2021 (UTC)
@Simon Villeneuve: The two queries find the same 7 distinct items for organizations which have statements using CQT as reference and values for ?direction, but the undistinct numbers are different in the two queries. The first query finds the 7 items multiple times. The seconds finds the items with CQT references only once due the use "distinct" in the subquery, but then the optional patterns in main query causes duplication of the items in the results. --Dipsacus fullonum (talk) 14:55, 24 February 2021 (UTC)

The First Human and the Label Service: What's going on here?Edit

Not sure if this is the best place to ask, don't recall seeing this being mentioned before but something strange seems to be happening with the Label Service in the follow query:

The following query uses these:

  • Properties: instance of (P31)     
    SELECT ?x ?xLabel WHERE {
      ?x wdt:P31 wd:Q5 .
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    } 
    LIMIT 1
    

I would expect George Washington to return almost immediately but 1) It takes a long time to run, sometimes even times out 2) It's not returning George Washington The following works as expected:

The following query uses these:

  • Properties: instance of (P31)     
    SELECT ?x ?xLabel WHERE {
      ?x wdt:P31 wd:Q5 .
      ?x rdfs:label ?xLabel .
      FILTER (LANG(?xLabel)="en")
    } 
    LIMIT 1
    

Piecesofuk (talk) 17:53, 23 February 2021 (UTC)

@Piecesofuk: The problem is that the label service is applied before the limit so many labels are found. You can optimize the query by using a standard subquery:
SELECT ?x ?xLabel WHERE {
  {
    SELECT ?x
    WHERE {
      ?x wdt:P31 wd:Q5 .
    }
    LIMIT 1
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Try it!
You can also use a named subquery. It isn't standard SPARQL, but a little faster:
SELECT ?x ?xLabel
WITH
{
  SELECT ?x
  WHERE {
    ?x wdt:P31 wd:Q5 .
  }
  LIMIT 1
}
AS %1
WHERE
{
  INCLUDE %1
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
Try it!
By the way, you shouldn't expect the result to be George Washington. There is no guaranteed order of query results and any entity with a truthy P31 Q5 statement can be returned. --Dipsacus fullonum (talk) 23:17, 23 February 2021 (UTC)
Thanks for the reply, surprised that there is no guaranteed order, I've always assumed there was, must remember that. What was really weird was that the label service usually returned the same item Mikhail Bulgakov (Q835), but sometimes it returned a deleted lexeme invalid ID (L411867) Piecesofuk (talk) 07:00, 24 February 2021 (UTC)
@Dipsacus fullonum: actually when I try both your queries they're returning that deleted lexeme!? Piecesofuk (talk) 07:04, 24 February 2021 (UTC)
@Piecesofuk: There are deleted entities (items and lexemes) which remain in the query service because there is bug in the WDQS updating system at the moment so entities aren't automatically removed from WCQS when deleted but have to be manually removed at regular intervals. It is discussed in the thread Wikidata:Contact the development team/Query Service and search#Q104776498 deleted but still on WQS (2021-02-14). --Dipsacus fullonum (talk) 07:56, 24 February 2021 (UTC)
Ah ok, thanks. I just "DESCRIBE"d it and see it does have P31 Q5 Piecesofuk (talk) 08:09, 24 February 2021 (UTC)

Items satisfying one property statement, but not having one qualifierEdit

Example: English alphabets (part of Q754673) items not having unicodehex (P4213) as qualifiers in the item pageVis M (talk) 09:13, 24 February 2021 (UTC)

@Vis M:
# Unicode characters for parts of English Alphabet without Unicode hex codepoint qualifier
SElECT ?item ?itemLabel ?unicode_character ?unicode_character_statement
WHERE
{
  ?item wdt:P361 wd:Q754673 . # ?item is part of English Alphabet
  ?item p:P487 ?unicode_character_statement .
  ?unicode_character_statement ps:P487 ?unicode_character .
  MINUS { ?unicode_character_statement pq:P4213 [] . } # Only results without Unicode hex codepoint qualifier
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
Try it! --Dipsacus fullonum (talk) 09:30, 24 February 2021 (UTC)
Thank you very much!! Vis M (talk) 10:12, 24 February 2021 (UTC)

Query not returning data for one object out of thousandsEdit

Hi, I am looking for objects based on their Netflix ID (P1874) returning their title (P1476) and if available also IMDb ID (P345), Rotten Tomatoes ID (P1258) and Metacritic ID (P1712). Query provided below works for over a year and provided correct data to over few thousands of queries/objects and Space Sweepers (Q65267432) is the first object that I found, that contains data (in this case IMDb ID (P345)) that I am trying to get, but query will not return them. Just to clarify, query still works with only exception of Space Sweepers (Q65267432) object. Is there an error in my query that I don't see? I am quite new to SPARQL so if you see any way how to make this shorter/more optimal I am open for suggestions. Thank you.

SELECT 
  (?item AS ?url) 
  (COALESCE(?title, "") AS ?title) 
  (COALESCE(?idIMDB, "N/A") AS ?idIMDB) 
  (COALESCE(?idRT, "N/A") AS ?idRT) 
  (COALESCE(?idMETA, "N/A") AS ?idMETA) 
WHERE { 
  ?item wdt:P1874 "81094067". 
  OPTIONAL {?item wdt:P1476 ?title.}  
  OPTIONAL {?item wdt:P345 ?idIMDB.} 
  OPTIONAL {?item wdt:P1258 ?idRT.} 
  OPTIONAL {?item wdt:P1712 ?idMETA.} 
}
Try it!

KayaNatsumi (talk) 10:19, 24 February 2021 (UTC)

@KayaNatsumi: When you use predicates with the prefix wdt: you only get values of "best rank", i.e. the values of preferred rank if any exist, and else the values of normal rank. You will never get results of deprecated rank. The value for IMDb ID (P345) in Space Sweepers (Q65267432) has deprecated rank. That is why your query doesn't return it. Use p:P345/ps:P345 to get all results independent of rank. --Dipsacus fullonum (talk) 10:36, 24 February 2021 (UTC)
@Dipsacus fullonum: Amazing! It works. Is there some manual/guide page that I could read about wdt and p/ps to understand it better? Again, thank you for help. KayaNatsumi (talk) 11:11, 24 February 2021 (UTC)
@KayaNatsumi: Yes, it is described in mw:Wikibase/Indexing/RDF Dump Format. --Dipsacus fullonum (talk) 11:20, 24 February 2021 (UTC)

--105.98.11.240 16:52, 24 February 2021 (UTC)