Skip to content

Help with SPARQL queries: common patterns

Hannah Bast edited this page Jun 4, 2022 · 1 revision

It can be hard to find the right SPARQL query. QLever's autocompletion is of great help to find the right predicate or entity name at each position of the query. But for some queries, it's also hard to find the right structure. Here is a list of common patterns with examples.

N-ary information

Example query: Oscars of Meryl Streep and the movies she won them for

Explanation: With a good autocompletion, it's not hard to find that Wikidata has a predicate P166 named "award received". The problem with the query above is that we are interested in three properties of an award: The person who won it, the name of the award, and the movie for which it was awarded. But predicates in RDF only connect two entities, not three. We, therefore, have to go via an intermediate so-called statement node, called ?m in the example query above.

Find a representative from each group with a certain property

Example query: Highest peak of each mountain range in Germany

Explanation: With a GROUP BY ?mountain_range, you can easily find for each mountain range, the highest elevation for each mountain range using (MAX(?elevation) AS ?max_elevation) in the SELECT clause. You could also find an example mountain for each mountain range by adding (SAMPLE(?mountain) AS ?example_mountain). But how do you find for each mountain range the mountain with the highest elevation? Turns out that is not so easy with SPARQL. The example query shows you how it's done.