Should variable bound in SELECT clause be accessible in ORDER BY?

37 views Asked by At

Should this be valid SPARQL?

SELECT ("text" AS ?aString)
WHERE {}
ORDER BY ?aString

I have tried two different engines. One returns "text" for ?aString, the other errors, saying that ?aString is not defined in the ORDER BY. Does the SPARQL spec cover this case? Or is this just an implementation detail, where it happens to work in some engines, but is not strictly portable?

2

There are 2 answers

2
Joshua Taylor On BEST ANSWER

Sparql.org's query validator says it's legal. This is actually a pretty important case, since we want to be able to do things like:

select ?min ?max ((?max - ?min) as ?range) {
  #-- ...
}
order by ?range
0
AndyS On

A SPARQL query (actually, one level, i.e. SELECT, of query) splits in pattern pattern and operations on the results of the pattern. Those operations are called modifiers.

They happen in the sequence:

order - project - distinct - reduces - offset - limit 

SELECT is complicated - it isn't just one modifier and it isn't just a projection. The AS in the example has two aspects and it becomes like BIND done as the final pattern stage and also includes the variable in the project.

This query has exactly the same SPARQL algebra form as the one in the query.

SELECT ?aString
WHERE {
    ...
    BIND ("text" AS ?aString)
}
ORDER BY ?aString

or in the algebra:

(project (?aString)
  (order (?aString)
    (extend ((?aString "text"))
      ...)))

which is evaluated inside-out.

?aString is defined before order happens and ORDER BY can sort using it.