Study Vault Search notes, aliases and full text
Graph
ConceptDBISAI-written · not yet proofread

SPARQL Query Structure

A basic SPARQL query `SELECT <variables> WHERE { <triples> }` is a graph pattern of triples with variables; its result is a table with one row per assignment of values to the variables such that all query triples exist in the knowledge graph.

Know these firstRDF Triple

Properties#

  • Graph pattern. The query triples form a small graph with variables at some nodes or edges. Answering the query means finding all matches of this pattern in the large KG; each distinct match is one assignment (one row).
  • Joins are implicit. Using the same variable in several triples is the join; there is no explicit join condition.

Syntax elements:

ElementSyntaxMeaning
variable?namebound to values during matching
fixed entity / predicate<Entity>, or prefixed wd:Q42, wdt:P31a known IRI
literal"1980", "Honolulu"@ena fixed value
query triples p o .one constraint; triples are separated by . (the last . before } is optional)
SELECT *selects all variables

Modifiers (as in SQL):

  • PREFIX wd: <http://www.wikidata.org/entity/> abbreviates long IRIs.
  • FILTER (condition) keeps only rows satisfying the condition, e.g. FILTER (LANG(?name) = "en") for English labels, FILTER (?a != ?b).
  • ORDER BY DESC(?x) / ASC(?x), LIMIT k; note that DESC/ASC is written like a function of the sort key.

Differences to SQL:

SPARQLSQL
dataone big “table” of triples (but: named graphs)many tables, FROM clause
main instrumenttriples with variablesFROM + WHERE conditions
joinsame variable in several triplesexplicit equality conditions (Join)
SELECT listno commas: SELECT ?a ?bcommas: SELECT a, b
sort orderDESC(?var)var DESC

Expressiveness. Basic SPARQL and SQL are essentially equivalent; basic queries translate mechanically (SPARQL to SQL Translation).

Example#

All people born in Honolulu with their English names and birth dates, youngest first:

PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?person ?person_name ?date_of_birth WHERE {
  ?person wdt:P19 wd:Q18094 .            # place of birth: Honolulu
  ?person wdt:P569 ?date_of_birth .      # date of birth
  ?person rdfs:label ?person_name .
  FILTER (LANG(?person_name) = "en")
}
ORDER BY DESC(?date_of_birth) LIMIT 100

Married couples who acted in the same film (?film and ?person1/?person2 are the shared variables, i.e. the joins):

SELECT ?person1 ?person2 ?film WHERE {
  ?person1 <acted_in>   ?film .
  ?person2 <acted_in>   ?film .
  ?person1 <married_to> ?person2 .
}

Simplest case: SELECT ?person ?occ WHERE { ?person <born_in> <Ulm> . ?person <occupation> ?occ . } returns each person born in Ulm with each of their occupations.

Sources#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only