Domain Chapter

Query Patterns

Master reusable SPARQL patterns that solve common challenges. From traversing hierarchies to deduplicating results, these patterns form the building blocks for complex real-world queries.

6
Topics
20+
Patterns
Advanced
Level

Building Blocks for Complex Queries

After mastering SPARQL syntax, the next step is learning reusable patterns that solve recurring problems. These patterns are the "design patterns" of SPARQL — proven solutions you can adapt to many situations.

This chapter covers:

Pattern Topics

Essential Patterns

Pattern 1: Instance-of with Subclass Traversal

Find All Museums (Including Subtypes)
Run ↗
SELECT ?museum ?museumLabel ?type ?typeLabel
WHERE {
  # Match museums AND all subclasses of museum
  ?museum wdt:P31/wdt:P279* wd:Q33506 .  # museum

  # Get the specific type
  ?museum wdt:P31 ?type .

  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}
LIMIT 20

Pattern 2: SAMPLE for Multi-Valued Properties

Get One Value Per Entity
Run ↗
SELECT ?lang ?langLabel
       (SAMPLE(?paradigmLabel) AS ?oneParadigm)
       (COUNT(?paradigm) AS ?paradigmCount)
WHERE {
  ?lang wdt:P31 wd:Q9143 ;
        wdt:P3966 ?paradigm .
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}
GROUP BY ?lang ?langLabel
ORDER BY DESC(?paradigmCount)
LIMIT 20

Pattern 3: Concatenate Multiple Values

Combine All Values into One Cell
Run ↗
SELECT ?lang ?langLabel
       (GROUP_CONCAT(DISTINCT ?paradigmLabel; SEPARATOR=", ") AS ?paradigms)
WHERE {
  ?lang wdt:P31 wd:Q9143 ;
        wdt:P3966 ?paradigm .
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}
GROUP BY ?lang ?langLabel
LIMIT 20

Pattern 4: Ranking by Computed Score

Rank Languages by "Popularity" Score
Run ↗
SELECT ?lang ?langLabel ?sitelinks ?statements
       (?sitelinks * 2 + ?statements AS ?score)
WHERE {
  ?lang wdt:P31 wd:Q9143 ;
        wikibase:sitelinks ?sitelinks ;
        wikibase:statements ?statements .
  SERVICE wikibase:label {
    bd:serviceParam wikibase:language "en" .
  }
}
ORDER BY DESC(?score)
LIMIT 20

Anti-Patterns to Avoid

Anti-Pattern Problem Better Approach
SELECT * Returns all variables, including internal ones Explicitly list needed variables
Unbound wdt:P279* Can traverse entire class hierarchy (slow) Always start from a specific entity
Missing LIMIT May return millions of rows Always add LIMIT during development
Cartesian products Unrelated patterns multiply results Ensure patterns share variables
FILTER(STR(?x) = "...") String comparison is slow Use direct entity references
Multiple OPTIONALs Each OPTIONAL can multiply results Use SAMPLE or GROUP_CONCAT

Quick Optimization Tips

Continue Learning

🌐

← Multilingual

Query across languages and scripts.

Go Back
📘

Start Over →

Review the basics or explore examples.

Basic Queries