query: # 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 440 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
  WHERE
  {
    # All episodes should be instance of episode with series Law & Order.
    ?episode wdt:P31 wd:Q1983062;
             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 [
                 ps:P179 [
                   # the season also has series Law & Order
                   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