Query Wikidata using SPARQL like a Genius
Houcemeddine Turki / Csisc
Co-Founder / Wikidata Arabic Community
Wikidata
CC0, Planemad for the Wikimedia Foundation
SPARQL lets users query Wikidata to extract or integrate localized cultural, historical, or linguistic facts for preservation or reuse.
Storing local knowledge
Developers use SPARQL to power search, visualization, and recommendation tools that leverage structured data from Wikidata.
Building tools and applications
SPARQL queries help detect missing entries, contradictory statements, or incomplete data for quality assurance in Wikidata.
Identifying gaps and inconsistencies
SPARQL
First
A Gentle Introduction to Wikidata for Absolute Beginners + Wikidata Query Tutorial
SPARQL – a gentle introduction to the Wikidata Query Service
First steps with SPARQL
Wikidata Query Service - the way forward for getting the most out of Wikimedia's knowledge graph
2017
2018
2023
2024
Previous Times
Second
Third
Fourth
User Interface SPARQL Basics
French
Advanced SPARQL
Vigneron
Italian
Epidosis
Swedish
Jan Ainali
Arabic
Csisc
Special Thanks to Tiago Lubiana and Adriano Rutz as well.
Time to show Advanced SPARQL in English
I will show how you can write a proper Wikidata code and debug it without using any feature of the Wikidata Query Service User Interface.
What we will do
https://query.wikidata.org
Query 1
“What does Wikidata know about Douglas Adams”
Principle 1: SPARQL Clauses
Principle 2: SPARQL Statements
Principle 2: SPARQL Statements
The type of the object depends on the predicate.
Principle 2: SPARQL Statements
Trick 1: URI Prefixes
Example: Choose the right URI Prefixes to retrieve statement references
https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Full_list_of_prefixes
Trick 2: Autocomplete Shortcuts
Solution: SELECT
Solution: FILTER
Task: Retrieve the English label of Douglas Adams (Q42).
SELECT ?itemLabel WHERE {
wd:Q42 rdfs:label ?itemLabel .
FILTER(LANG(?itemLabel) = "en")
}
Tip: Always filter by language for cleaner results.
Douglas Adams
PROPERTY | VALUE |
rdfs:label | Label |
schema:description | Description |
skos:altLabel | Alias |
dct:language | Language (Lexemes) |
Operators
OPERATOR | VALUE |
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
&& | AND |
!= | Different from |
> | Greater than |
OPERATOR | VALUE |
() | Parentheses |
= | Equal to |
|| | OR |
! | NOT |
>= | Superior or equal to |
<= | Inferior or equal to |
< | Lower than |
Alternative 1: ASK
❓ Task: Is Douglas Adams (Q42) a human (Q5)?
ASK {
wd:Q42 wdt:P31 wd:Q5 .
}
💡 Tip: ASK returns true or false. Useful for boolean checks or validations.
Alternative 2: DESCRIBE
❓ Task: Give me everything known about Douglas Adams.
DESCRIBE wd:Q42
💡 Tip: DESCRIBE returns RDF triples about a resource. Used for exploration.
You can also use DESCRIBE with a SPARQL statement.
DESCRIBE ?president {?president wdt:P106 wd:Q11696}
Query 2
“Show a list of 1000 ancestors of Queen Elizabeth II”
P22
P25
Ancestors
Elizabeth II
father
mother
father
mother
Ancestor
Trick 3: Sorting and Pagination
Keyword | Purpose | Example Usage | Explanation |
ORDER BY | Sorts the query results | ORDER BY DESC(?person) | Sorts the results in descending order (newest first). Use ASC() for ascending order. |
LIMIT | Restricts the number of results returned | LIMIT 10 | Only the first 10 results are shown. |
OFFSET | Skips a number of results | OFFSET 10 | Starts at the eleventh result. Use OFFSET 20 to skip the first 20, and so on for pagination. |
Trick 4: Property Path Operators
Operator | Usage | Meaning | Example |
+ | ?a wdt:P31+/wdt:P279* ?b | One or more occurrences of the predicate | Matches indirect instance chains |
* | ?a wdt:P279* ?b | Zero or more occurrences | Matches a class and any of its subclasses |
^ | ?a ^wdt:P31 ?b | Inverse of the predicate | Traverses from object to subject |
/ | ?a wdt:P31/wdt:P279 ?b | Sequence of properties | Follow a chain of two properties |
Trick 4: Property Path Operators
Operator | Usage | Meaning | Example |
! | ?a !wdt:P31 ?b | Negation: match any property except this one | Excludes the specified predicate |
() | ?a (wdt:P31/wdt:P279)* ?b | Grouping | Groups property paths together |
[ ] | Used in triple patterns: ?a ?p [ wdt:P31 wd:Q5 ] If empty ([ ]): Any value | Anonymous node or property filter | Match with intermediate blank nodes or nested properties |
| | ?a (wdt:P31|wdt:P279) ?b | OR | Match on one of several properties |
Solution: Query using Property Path Operators
Query 3
“Provide a list of Tunisian singers born after 1985”
Solution 1: Basic Query
Variable names are separated by spaces
Solution 2: Using VALUES for Multiple Occupations
Solution 3: Using FILTER on Date Directly
Trick 5: Defining constant values
"xyz"
string
0.0
float
-0
int
"x"
char
Solution 4: Using BIND to Extract the Year and HAVING to Filter
AS: Defines a variable name for an expression
Query 4
“Visualize cities in Tunisia on a map”
Solution: Geographical Coordinates
Solution: defaultView
🔍 Tip: #defaultView:Map at the top chooses how to display results.
Query 5
“Find twenty humans who do not have a known date of death”
Solution 1: Using FILTER NOT EXISTS
Filters out odd values from the results.
Solution 2: Using MINUS
Filters out odd values from the items meeting the previous condition.
Query 6
“Get fifty people under 18 or over 65.”
Solution 1: OR
Solution 2: UNION
Query 7
“Identify the gender of fifty people and assign UNKNOWN as a value if not available”
Solution 1: Optional, BOUND
Solution 2: Optional, COALESCE
Query 8
“Identify fifty English people having a first name that begins with A”
https://en.wikibooks.org/wiki/SPARQL/Expressions_and_Functions
Solution 1: REGEX
Solution 1: REGEX
https://w.wiki/EpJi
Solution 2: STRSTARTS
Solution 2: STRSTARTS
https://w.wiki/EpJj
Query 9
“Calculate the number of world heritage sites by country”
Trick 6: Aggregate Functions
Function | Description | Notes |
COUNT(*) | Counts all matching results. | Use COUNT(?var) to count non-null values of a specific variable. |
SUM(?var) | Calculates the sum of all numeric values. | Returns an error or NaN if applied to non-numeric values. |
AVG(?var) | Computes the average of all numeric values. | Similar restrictions as SUM. |
MIN(?var) | Finds the minimum value. | Works on numbers, strings, and other comparable types. |
Trick 6: Aggregate Functions
Function | Description | Notes |
MAX(?var) | Finds the maximum value. | Lexical order for strings; numeric order for numbers. |
SAMPLE(?var) | Returns an arbitrary value from the group. | Useful when you expect one value or don’t care which value is returned. |
GROUP_CONCAT(?var) | Concatenates all values into a single string (usually comma-separated). | Optional parameters allow setting custom separators, e.g., GROUP_CONCAT(?var; separator=", "). |
Step 1: How to identify items
Use a known example
Step 2: Extract all heritage sites
Step 3: GROUP BY
What will be counted
Based on
Step 4: Define the aggregate function
Step 5: ORDER BY
Step 6: HAVING
Query 10
“Find all countries whose number of official languages is above the average number of official languages across all countries.”
Solution: Subqueries
𝟙. Compute the average number of official languages across all countries
𝟚. Reuse the result in the main query
𝟛. Calculate the number of official language for every country
𝟜. Filter out the countries having a number of official languages below the average
Step 1: Calculate the average
𝟙. Compute the number of official languages for every country
𝟚. Calculate the average number of official language across countries
Step 1.1: Number of Languages
Step 1.2: Calculate the average
Add a subquery inside the body of a SPARQL query:
Step 1.2: Calculate the average
Add a subquery inside the body of a SPARQL query:
Step 2: Reuse in the main query
Add a subquery inside the body of a SPARQL query:
Step 2: Reuse in the main query
Use WITH:
Not Standard
SPARQL
Step 3: Number of Languages
Same as 1.1
Step 4: Filter out countries below the average
Step 4: Filter out countries below the average
Query 11
“Find all medications that have significant drug interactions with the ones curing fever.”
Solution
https://w.wiki/EpK3
🔹 hint:Prior hint:runFirst true
This hint gives execution priority to a particular part of the query, usually a triple pattern or group.
🔹 hint:Prior hint:runLast true
This is the opposite of runFirst.
Running the statement with the most constants last
https://w.wiki/EpKB
Running the statement with the most constants first
https://w.wiki/EpKD
Query 12
“Find all the scholarly publications of Nobel Prize winners in Chemistry from 2013 to 2022.”
query.wikidata.org
Main graph (all non-scholarly data)
query-scholarly.wikidata.org
Scholarly graph, includes scholarly articles and work
Why the split?�Wikidata’s growth (16B+ triples, +1B/year) made it too large for one query service (WDQS) to handle reliably, leading to slow queries, crashes, and long rebuild times.
🔄 Wikidata Graph Split (May 2025)
What changed?�As of 9 May 2025, the graph is split into two:
The scholarly graph endpoint has become an external SPARQL endpoint for the main SPARQL endpoint
Solution
SERVICE keyword is used to call external SPARQL endpoints or special internal services. This allows you to integrate data from multiple sources or use specific built-in services provided by Wikidata. Here's how it works:
SERVICE Type | Syntax | Purpose | Common Parameters | Example Use |
Label Service | SERVICE wikibase:label | Fetch labels/descriptions in human languages | bd:serviceParam wikibase:language "en" | Show item labels instead of Q-IDs |
MediaWiki API Service | SERVICE wikibase:mwapi | Access MediaWiki API (search, sitelinks, etc.) | wikibase:api, mwapi:search, mwapi:item, wikibase:apiOutputItem | Search entities by label |
External SPARQL Service | SERVICE <https://external.sparql.endpoint> | Query external SPARQL endpoints (e.g., DBpedia) | None specific — write standard SPARQL inside | Combine data from Wikidata + DBpedia |
Applications
Type | Example |
Label Service | SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } |
mwapi Search | SERVICE wikibase:mwapi { bd:serviceParam wikibase:api "EntitySearch"; mwapi:search "Paris"; mwapi:language "en". ?item wikibase:apiOutputItem mwapi:item. } |
External | SERVICE <https://dbpedia.org/sparql> { ?s rdfs:label "Tunis"@en. } |
Examples
Solution
https://w.wiki/EpKe
Jamal Nxedlana, from Bubblegum Club, on behalf of Moleskine Foundation, CC BY-SA 4.0
Time for work.
Spread the word.
Q&A