SPARQL/FILTER

is a clause you can insert into your SPARQL query to, well, filter the results. Inside the parentheses, you can put any expression of boolean type, and only those results where the expression returns  are used.

FILTER on values
For example, to get a list of all humans born in 2015, we first get all humans with their date of birth –

– and then filter that to only return the results where the year of the date of birth is 2015. There are two ways to do that: extract the year of the date with the  function, and test that it’s 2015 –

– or check that the date is between Jan. 1st (inclusive), 2015 and Jan. 1st, 2016 (exclusive):

I’d say that the first one is more straightforward, but it turns out the second one is much faster, so let’s use that:

FILTER on values in Labels
Another possible use of  is related to labels. The label service is very useful if you just want to display the label of a variable. But if you want to do stuff with the label – for example: check if it starts with “Mr. ” – you’ll find that it doesn’t work:

This query finds all instances of Q15632617 and tests if their label starts with  (  is short for “string starts [with]”; there’s also   and  ). The reason why this doesn’t work is that the label service adds its variables very late during query evaluation; at the point where we try to filter on, the label service hasn’t created that variable yet.

Fortunately, the label service isn’t the only way to get an item’s label. Labels are also stored as regular triples, using the predicate. Of course, this means all labels, not just English ones; if we only want English labels, we’ll have to filter on the language of the label:

The  function returns the language of a monolingual string, and here we only select those labels that are in English. The full query is:

We get the label with the  triple, restrict it to English labels, and then check if it starts with “Mr. ”.

FILTER NOT EXISTS
Let's add images to these fictional humans

The code  shows all the fictional humans that start with “Mr. ” and shows an image if available. To select only fictional humans starting with “Mr. ” with an image the code   can be used. To select those fictional humans without an image the code  should be used

MINUS
A similar way of negation provided in SPARQL is  which evaluates both its arguments, then calculates solutions in the left-hand side that are not compatible with the solutions on the right-hand side.