Search code examples
nullsparqlrdf

SPARQL : Handle NULL values returned by OPTIONAL() keyword


Here is my simple working Sparql query:

SELECT DISTINCT ?period ?start ?end
WHERE {
    ?period isA "Period".
    OPTIONAL { ?period hasStart ?start }. #hasStart
    OPTIONAL { ?period hasEnd ?end }. #hasEnd
}

The thing is I'd like to add a variable in the select clause which is the duration between ?end and ?start, like this :

SELECT ... (year(?end)-year(?start) as ?duration)

As ?end and ?start may not be present in my DB, their value could be NULL and I'm getting this error : Function year needs a datetime, date or time as argument 1, not an arg of type DB_NULL.

Is there a way to handle NULL values returned by an optional() keyword ? Thank you very much !


Solution

  • Yoy can use BOUND(?end) and BOUND(?start) for checking if such variables are bound.

    SELECT DISTINCT
      ?period ?start ?end
      (IF(BOUND(?end) && BOUND(?start), year(?end)-year(?start), ?null) as ?duration)
    WHERE {
        ?period isA "Period".
        OPTIONAL { ?period hasStart ?start }. #hasStart
        OPTIONAL { ?period hasEnd ?end }. #hasEnd
    }