TWdorado
TWdorado

Reputation: 117

Filtering on optional data?

How can I filter on optional values in SPARQL, while keeping results where the optional value isn't present? E.g., in the following data there are three books, and the third has no price:

:book1 a :Book ; :hasPrice 10.
:book2 a :Book ; :hasPrice 20.
:book3 a :Book.

How can I select books that either have a price less than 15 or have no price at all?

Upvotes: 1

Views: 835

Answers (1)

Joshua Taylor
Joshua Taylor

Reputation: 85883

select ?book ?price where { 
  ?book a :Book .
  optional { ?book :hasPrice ?price }
  filter ( !bound(?price) || ?price < 15 )
}
------------------
| book   | price |
==================
| :book3 |       |
| :book1 | 10    |
------------------

Upvotes: 6

Related Questions