Example SPARQL queries that can help you list the classes in an ontology.

List all classes

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
  
SELECT DISTINCT ?type
WHERE {
  ?s a ?type.
}

Note: The SPARQL keyword a is a shortcut for the common predicate rdf:type, giving the class of a resource.

List root classes

SELECT ?directSub ?super
 WHERE { ?directSub rdfs:subClassOf ?super .
         FILTER NOT EXISTS {
            ?directSub rdfs:subClassOf ?otherSub .
            FILTER (?otherSub != ?directSub)
         }
}

List all classes with a given prefix

PREFIX bc: <http://base22.com/ont/bc#>
 
SELECT DISTINCT ?type
WHERE {
  ?subject a ?type.
  FILTER( STRSTARTS(STR(?type),str(bc:)) )
}

List class hierarchy

PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
 
 
SELECT DISTINCT ?subject ?label ?supertype
WHERE {
    { ?subject a owl:Class . } UNION { ?individual a ?subject . } .
    OPTIONAL { ?subject rdfs:subClassOf ?supertype } .
    OPTIONAL { ?subject rdfs:label ?label }
} ORDER BY ?subject

Note that when a reasoner is enabled classes may typically be inferred to be rdfs:subClassOf themselves and rdfs:subClassOf any parent class, not just the direct parent.

List class hierarchy – filtered

Give a class hierarchy, but filter out several structural elements so that we only end up with the unique classes in our ontology.

PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?subject ?label ?supertype
WHERE {
    { ?subject a owl:Class . } UNION { ?individual a ?subject . } .
    OPTIONAL { ?subject rdfs:subClassOf ?supertype } .
    OPTIONAL { ?subject rdfs:label ?label }.
    FILTER (?subject != owl:Class &&
        ?subject != rdf:List &&
        ?subject != rdf:Property &&
        ?subject != rdfs:Class &&
        ?subject != rdfs:Datatype &&
        ?subject != rdfs:ContainerMembershipProperty &&
        ?subject != owl:DatatypeProperty &&
        ?subject != owl:NamedIndividual &&
        ?subject != owl:Ontology )
} ORDER BY ?subject

Note that when a reasoner is enabled classes may typically be inferred to be rdfs:subClassOf themselves and rdfs:subClassOf any parent class, not just the direct parent.

List class hierarchy with direct subclasses only

This is similar to the query above, but uses the Sesame-specific sesame:directSubClassOf to get only direct subclasses. This would work in any RDF4J (formerly Sesame) system such as Graph DB.

PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX : <http://codyburleson.com/hyperg/>
 
SELECT DISTINCT ?subject ?label ?supertype
WHERE {
    {
        ?subject a owl:Class .
        OPTIONAL { ?subject sesame:directSubClassOf ?supertype } .
        OPTIONAL { ?subject rdfs:label ?label }.
    }
           
          FILTER (?subject != owl:Class &&
            ?subject != rdf:List &&
            ?subject != rdf:Property &&
            ?subject != rdfs:Class &&
            ?subject != rdfs:Datatype &&
            ?subject != rdfs:ContainerMembershipProperty &&
            ?subject != owl:DatatypeProperty &&
            ?subject != owl:NamedIndividual &&
            ?subject != owl:Ontology &&
            ?subject != ?supertype)
} ORDER BY ?subject

 

SPARQL examples – construct

Construct a graph giving ontology structure (the class hierarchy, properties, domains and ranges)

CONSTRUCT { ?s ?p ?o . } 
WHERE { VALUES ?p { rdfs:subClassOf rdfs:subPropertyOf rdfs:domain rdfs:range} ?s ?p ?o }

Note that when a reasoner is enabled classes may typically be inferred to be rdfs:subClassOf themselves and rdfs:subClassOf any parent class, not just the direct parent.

SPARQL examples – select

Find all triples

Use SELECT to signify you want to SELECT certain information and WHERE to signify your conditions, restrictions, and filters. A limit is used to avoid cracking the server on a large dataset.

SELECT ?subject ?predicate ?object
WHERE {?subject ?predicate ?object} 
LIMIT 100

Find all same-subject triples by given subject

By specifying only the subject in the pattern, we can return all triples that have that subject. When an individual entity is defined by a given subject URI, then this is a way to get all the properties for that entity.

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?subject ?predicate ?object
WHERE {
    <http://codyburleson.com/hyperg/person/cody-burleson> ?predicate ?object .
} LIMIT 100

Since the subject is known, it may typically only be necessary to return the ?predicate and ?object in the SELECT line (omitting ?subject)

Find and order most used predicates

SELECT ?predicate (COUNT(*)AS ?frequency)
WHERE {?subject ?predicate ?obDEject}
GROUP BY ?predicate
ORDER BY DESC(?frequency)
LIMIT 10

Select the top 100 nodes in the RDF graph

RDF Rank is a GraphDB extension. It is similar to Page Rank and it identifies “important” nodes in an RDF graph based on their interconnectedness. It is accessed using the rank:hasRDFRank system predicate.

PREFIX rank:<http://www.ontotext.com/owlim/RDFRank#>
SELECT ?n
WHERE {?n rank:hasRDFRank ?r }
ORDER BY DESC(?r)
LIMIT 100

Find anything with a label

The following query will find all triples where subject and object are joined by rdfs:label. In other words, anything that has been defined as having a label.

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?subject ?label
WHERE { ?subject rdfs:label ?label } LIMIT 100

Find instances by class with a label

The following example query will get the labels of anything of the class type (rdf:type) Organization.

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?subject ?label
WHERE {
    ?subject rdf:type <http://codyburleson.com/hyperg#Organization> .
    ?subject rdfs:label ?label
} LIMIT 100

Find all subjects with a given object property

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX bc: <http://www.base22.com/ontologies/2010/5/bc.owl#>

SELECT ?subject
WHERE { ?subject bc:hasEmployer <http://www.base22.com/ontologies/2010/5/my-contacts.owl#IBM> } LIMIT 100

From my contacts ontology, I find all IBMers (i.e. the hasEmployer predicate points to the individual IBM, which is an object of type Organization).

Find all classes

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
 
SELECT DISTINCT ?type
WHERE {
  ?s a ?type.
}

The SPARQL keyword a is a shortcut for the common predicate rdf:type, giving the class of a resource.

Find all classes with a given prefix

PREFIX bc: <http://base22.com/ont/bc#>
 
SELECT DISTINCT ?type
WHERE {
  ?subject a ?type.
  FILTER( STRSTARTS(STR(?type),str(bc:)) )
}

The SPARQL keyword a is a shortcut for the common predicate rdf:type, giving the class of a resource.

Query from a particular graph on the web

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX card: <http://www.w3.org/People/Berners-Lee/card#>

SELECT ?homepage
FROM <http://www.w3.org/People/Berners-Lee/card>
WHERE {
 card:i foaf:knows ?known .
 ?known foaf:homepage ?homepage .
}

The FROM keyword lets us specify the target graph in the query itself.
Of interest also in the query shown above:
By using ?known as an object of one triple and the subject of another, we traverse multiple links in the graph.

Find subjects with a property value greater than

Find me all landlocked countries with a population greater than 15 million

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>

SELECT ?country_name ?population
WHERE {
 ?country a type:LandlockedCountries ;
 rdfs:label ?country_name ;
 prop:populationEstimate ?population .
 FILTER (?population > 15000000) .
}

You can try this one at the DBPedia SPARQL endpoint.

  • FILTER constraints use boolean conditions to filter out unwanted query results.
  • Shortcut: a semicolon (;) can be used to separate two triple patterns that share the same subject. (?country is the shared subject above.)
  • rdfs:label is a common predicate for giving a human-friendly label to a resource.

SPARQL examples – filter

Return items with recorded date less than given date

PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX web: <http://base22.com/ont/web#>
 
SELECT * WHERE {
    ?subject dcterms:title ?title.
    ?subject dcterms:abstract ?abstract.
    ?subject web:publishDate ?publishDate.
    FILTER (?publishDate < "2016-09-28T19:19:02.982Z"^^xsd:dateTime)
}

 

SPARQL examples – limit

Limit the number of results returned

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX bc: <http://www.base22.com/ontologies/2010/5/bc.owl#>

SELECT *
WHERE {
  ?subject bc:hasEmployer <http://www.base22.com/ontologies/2010/5/my-contacts.owl#IBM> .
           ?subject bc:hasBusinessEmail ?email .
} LIMIT 5

The LIMIT keyword is used after the WHERE clause, followed by a numerical value. In this case, of course, only 5 results are returned.

  • LIMIT is a solution modifier that limits the number of rows returned from a query. SPARQL has two other solution modifiers:
    • ORDER BY for sorting query solutions on the value of one or more variables
    • OFFSET, used in conjunction with LIMIT and ORDER BY to take a slice of a sorted solution set (e.g. for paging)

Find the person entries in Tim Berners-Lee’s FOAF file that do not contain a URL for the person’s FOAF file. Try this on ARQ.

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT ?name
FROM <http://www.w3.org/People/Berners-Lee/card>
WHERE {
  ?person a foaf:Person ; foaf:name ?name .
  MINUS { ?person rdfs:seeAlso ?url }
}

 

SPARQL examples – paging

Retrieve the second page of names and emails of people in Tim Berners-Lee’s FOAF file, given that each page has 10 people. Try this on ARQ.

PREFIX foaf:  <http://xmlns.com/foaf/0.1/>

SELECT ?name ?email
FROM <http://www.w3.org/People/Berners-Lee/card>
WHERE {
    {      SELECT DISTINCT ?person ?name WHERE {
        ?person foaf:name ?name
      } ORDER BY ?name LIMIT 10 OFFSET 10    }
    OPTIONAL { ?person foaf:mbox ?email }
}

 

SPARQL examples – ask

Is the Amazon river longer than the Nile river?

You can also try this one against DBPedia…

PREFIX prop: <http://dbpedia.org/property/>
ASK
{
  <http://dbpedia.org/resource/Amazon_River> prop:length ?amazon .
  <http://dbpedia.org/resource/Nile> prop:length ?nile .
  FILTER(?amazon > ?nile) .
}

The answer is: false.

Note: The WHERE keyword is optional–not only in ASK queries but in all SPARQL queries.

Does a triple with the given subject URI exist?

ASK { <http://example.org/carbon/ldp/main/people> ?p ?o> }

Returns true or false.

Does Fred have grandchildren?

PREFIX: <http://bedrock/>  
ASK  
WHERE {  :fred :hasChild :?child . :?child :hasChild :?grandchild. }

Where :fred has any child, see if that child has any child identified by the placeholder, :?child, then use the value of that placeholder to ask whether or not that child itself also has a child, which will be the :?grandchild.

Federate data from 2 endpoints

Find the birth dates of all of the actors in Star Trek: The Motion Picture.
Try this on ARQ.

PREFIX movie: <http://data.linkedmdb.org/resource/movie/>
PREFIX dbpedia: <http://dbpedia.org/ontology/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?actor_name ?birth_date
FROM <http://www.w3.org/People/Berners-Lee/card> # placeholder graph
WHERE {
  SERVICE <http://data.linkedmdb.org/sparql> {
    <http://data.linkedmdb.org/resource/film/675> movie:actor ?actor .
    ?actor movie:actor_name ?actor_name
  }
  SERVICE <http://dbpedia.org/sparql> {
    ?actor2 a dbpedia:Actor ; foaf:name ?actor_name_en ; dbpedia:birthDate ?birth_date .
    FILTER(STR(?actor_name_en) = ?actor_name)
  }
}

The SERVICE keyword is used to send part of a query against a remote SPARQL endpoint.