Subqueries
Subqueries are a way to embed SPARQL queries within other queries, normally to achieve results which cannot otherwise be achieved, such as limiting the number of results from some sub-expression within the query.
Due to the bottom-up nature of SPARQL query evaluation, the subqueries are evaluated logically first, and the results are projected up to the outer query.
Note that only variables projected out of the subquery will be visible, or in scope, to the outer query.
Example
Data:
@prefix : <http://people.example/> .
:alice :name "Alice", "Alice Foo", "A. Foo" .
:alice :knows :bob, :carol .
:bob :name "Bob", "Bob Bar", "B. Bar" .
:carol :name "Carol", "Carol Baz", "C. Baz" .
Return a name (the one with the lowest sort order) for all the people that know Alice and have a name.
Query:
PREFIX : <http://people.example/>
PREFIX : <http://people.example/>
SELECT ?y ?minName
WHERE {
:alice :knows ?y .
{
SELECT ?y (MIN(?name) AS ?minName)
WHERE {
?y :name ?name .
} GROUP BY ?y
}
}
Results:
| y | minName |
|---|---|
| :bob | "B. Bar" |
| :carol | "C. Baz" |
This result is achieved by first evaluating the inner query:
SELECT ?y (MIN(?name) AS ?minName)
WHERE {
?y :name ?name .
} GROUP BY ?y
This produces the following solution sequence:
| y | minName |
|---|---|
| :alice | "A. Foo" |
| :bob | "B. Bar" |
| :carol | "C. Baz" |
Which is joined with the results of the outer query:
| y |
|---|
| :bob |
| :carol |
Copyright © 2013 W3C® (MIT, ERCIM, Keio, Beihang). This software or document includes material copied from or derived from SPARQL 1.1 Query.