'Multiple sorting (with date) not working in inner query in SPARQL?

I was trying to execute following query in Wikidata Query Service.

SELECT ?s ?birthyear
WHERE {
   SELECT ?s ?birthyear
   WHERE {
     ?s wdt:P27 wd:Q837 .
     ?s wdt:P106 wd:Q33999 .
     ?s wdt:P569 ?dateOfBirth .
     BIND(YEAR(?dateOfBirth) as ?birthyear) 
   }
   order by asc(?birthyear) asc(?s)   
}

I was expecting to have sorting by birth year(ascending) and if anyone has same birth year, then sort them by subject but it is showing random order. also it is working fine in outer query. Issue is seen only in inner query. Is this expected behavior or Am I missing something?



Solution 1:[1]

There's no requirement in spraql for the inner select's result order to be projected and maintained into the outer select's results. If you want the results ordered, you should move the order by to the outer select. As to why you get unordered results, I'd guess that the query engine is smart enough to recognize that the inner order by doesn't affect the final results and can optimize it away.

Update: you can get a query plan out of wikidata, so looking at that it does do the inner order by, but ends up then running the results through a hashset which will then destroy the iteration order.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1