SPARQL Unbound variables || Query to bind a variable if it's unbound

Viewed 523

I'm trying to write a query binding a variable to a value if it hasn't been bound yet.
For example, it could look like this pseudocode:

OPTIONAL {
  FILTER (some filter)
  BIND ("I bound this variable" as ?variable)
}
OPTIONAL {
  FILTER (!BOUND(?variable))
  BIND ("This variable was unbound, but is now bound"
}

Basically, I have a variable that might or might not have an assigned value and if it didn't, I want to assign one, but I cannot make a query using an approach like FILTER (!BOUND(?variable)) work.

1 Answers

What you are looking for is the COALESCE function. For instance, imagine you have this data:

@prefix : <http://example.com/> .

:john a :Person ;
      :hasChild :anna , :will .
:anna a :Person ;
      :hasChild :charlie .
:will a :Person .
:charlie a :Person .

Then the SPARQL query:

SELECT ?person ?child
WHERE {
?person a :Person .
OPTIONAL { ?person :hasChild ?c }
BIND(COALESCE(?c, "Has no children.") AS ?child)
}

Note that COALESCE can take more than 2 arguments, e.g. if we slightly alter our data to:

@prefix : <http://example.com/> .
    
:john a :Person ;
      :hasDaughter :anna ;
      :hasSon :will .
:anna a :Person ;
      :hasSon :charlie .
:will a :Person .
:charlie a :Person .

i.e. we say if the child is a son or a daughter, then we can issue a query like:

SELECT ?person ?child
WHERE {
?person a :Person .
OPTIONAL { ?person :hasDaughter ?daughter }
OPTIONAL { ?person :hasSon ?son }
BIND(COALESCE(?daughter, ?son, "Has no children.") AS ?child)
}

This returns a daughter if there is one. Failing that, it will return a son, and failing that too, it will return the "Has no children."

Related