Concept Overview
In SPARQL, logical combinations (OR, AND, DIFFERENCE) aren’t special operators — they’re implemented through query structure.
Logic | Typical Use Case | SPARQL Technique |
---|
OR | Include entities matching any attribute | VALUES or UNION
|
AND | Require all attributes to be present | Subquery + HAVING(COUNT(...)) |
DIFFERENCE | Include some, exclude others | Combine AND + FILTER NOT EXISTS |
OR Logic - “Include any of these attributes”
Goal: Retrieve movies that belong to Drama OR Action genres.
PREFIX ex: <http://example.org/movie/>
SELECT ?title ?genre
WHERE {
?m a ex:Movie ;
ex:title ?title ;
ex:genre ?genre .
VALUES ?genre { "Drama" "Action" }
}
ORDER BY ?title
Output:
Title | Genre |
---|
The Dark Knight | Action |
The Shawshank Redemption | Drama |
Why it works:
The VALUES
clause binds multiple acceptable values to a variable. SPARQL evaluates the query once per binding — effectively performing OR logic without needing FILTER(?g="A" || ?g="B")
AND Logic - “Require all of these attributes”
Goal: Find movies that are tagged with both Drama and Crime genres. (Our dataset doesn’t have one that matches both, so you can test with modified data.)
PREFIX ex: <http://example.org/movie/>
SELECT ?title
WHERE {
{
SELECT ?m (COUNT(DISTINCT ?genre) AS ?genreCount)
WHERE {
?m a ex:Movie ; ex:genre ?genre .
FILTER(?genre IN ("Drama","Crime"))
}
GROUP BY ?m
HAVING(?genreCount = 2) # must have both genres
}
?m ex:title ?title .
}
Result (on current dataset):
(Empty result set — none of our 5 movies are both Drama and Crime) If you add a movie tagged as both, it will appear here.
Why it works:
The subquery groups by subject (?m
) and counts how many target genres it has.
The HAVING
clause enforces that all required ones are present — true AND logic.
DIFFERENCE Logic - “Include some, exclude others”
Goal: Return movies that are Crime or Drama but not Action.
PREFIX ex: <http://example.org/movie/>
SELECT ?title ?genre
WHERE {
?m a ex:Movie ;
ex:title ?title ;
ex:genre ?genre .
FILTER(?genre IN ("Drama","Crime"))
FILTER NOT EXISTS { ?m ex:genre "Action" }
}
ORDER BY ?title
Output:
Title | Genre |
---|
The Shawshank Redemption | Drama |
The Godfather | Crime |
Pulp Fiction | Crime |
Why it works:
- The first
FILTER
includes any movie that’s Drama or Crime. - The
FILTER NOT EXISTS
excludes any that also have the “Action” genre.
This creates a set difference (Include − Exclude).