MIN/MAX in SPARQL

Reading through Lee’s new SPARQL FAQ I didn’t really expect to learn anything new, but here we go:

How can I use SPARQL to query maximum/minimum values or other universally quantified criteria?

A combination of the SPARQL OPTIONAL keyword and the bound(...) filter function can be used to mimic some universally quantified queries. As an example, consider this query which finds the minimum price of every book in the underlying default graph:

PREFIX ex: <http://example.org/>
SELECT ?book ?minprice
WHERE {
    ?book a ex:book ; ex:price ?minprice .
    OPTIONAL { 
        ?book ex:price ?otherprice . 
        FILTER( ?otherprice < ?minprice ) .
    } .
    FILTER ( !bound(?otherprice) ) .
}

A hack, but still neat!

This entry was posted in General, Semantic Web. Bookmark the permalink.