I encountered the same problem and none of the solutions here addressed my issue. Here is my solution; it was non-trivial and quite a hack. This works for DBPedia as of now, and may work for other SPARQL endpoints, but it is not guaranteed to work for future releases.
DBPedia uses Virtuoso, which supports an undocumented argument to the RAND
function; the argument effectively specifies the range to use for the PRNG. The game is to trick Virtuoso into believing that the input argument cannot be statically-evaluated before each result row is computed, forcing the program to evaluate RAND()
for every binding:
select * {
?s dbo:isPartOf ?o . # Whatever your pattern is
bind(rand(1 + strlen(str(?s))*0) as ?rid)
} order by ?rid
The magic happens in rand(1 + strlen(str(?s))*0)
which generates the equivalent of rand()
; but forces it to run on every match by exploiting the fact that the program cannot predict the value of an expression that involves some variable (in this case, we just compute the length of the IRI as a string). The actual expression is not important, since we multiply it by 0
to ignore it completely, then add 1
to make rand
execute normally.
This only works because the developers did not go this far in their static-code-evaluation of expressions. They could have easily written a branch for "multiply by zero", but alas they did not :)