Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading