SPARQL/Subqueries

SPARQL allows one SELECT query to be nested inside another. The inner SELECT query is called a subquery and is evaluated first. The subquery result variable(s) can then be used in the outer SELECT query.

Simplest example:

The example below calculates the population of each country in the world, expressing the population as a percentage of the world's total population. In order to calculate the world's total population, it uses a subquery.

The syntax of a query with a subquery is shown below. A subquery is basically the same as a simple query and is enclosed within { brackets }.

SELECT ... query result variables ... WHERE {       ... query pattern ...

{ # subquery SELECT ... subquery result variables ... WHERE {                 ... subquery pattern ... }                 ... optional subquery modifiers ... } # end of subquery

}       ... optional query modifiers ...

Subqueries can be used, often with a, to avoid a query timeout by fractioning the task. As an example, this query is timing out :

but the same query putting the limit on the selected items in a subquery and the label service outside it didn't timeout :