Skip to content
AI & DataUpdated at

How to Query RDF: A Comprehensive Guide to SPARQL

RDF (Resource Description Framework) records facts as triples. A triple has a subject, a predicate naming a relationship or attribute, and an object. SPARQL is the standard query language for RDF. A SPARQL query describes a pattern of triples and returns the values that fit that pattern. A match assigns a value to a variable. That assignment is called a binding.

We'll query a small directory of blogs. Finding a blog title takes one pattern. Finding the name of its owner takes two patterns that meet at the same person. If you've worked with SQL, you might recognize that second operation as a join. The RDF guide explains how the directory's triples are represented.

SPARQL Query Structure

A SPARQL query generally consists of the following parts:

  1. PREFIX: Shortens long URIs for readability and usability.
  2. SELECT/ASK/CONSTRUCT/DESCRIBE: Defines the type of result (e.g., tabular, graph, or boolean).
  3. WHERE: Specifies the graph patterns to match.
  4. ORDER BY/LIMIT/OFFSET: Controls result sorting and pagination.

Basic SPARQL Queries

Here are the directory's eight triples in Turtle, a text notation for RDF. The prefixes abbreviate full resource identifiers (IRIs). site:blog names Ahmad's blog, and :ahmadassaf names Ahmad Assaf. The second blog, Overfit.in, has a different hypothetical owner. We use the display name "Other owner" for that example record.

The directory uses aa:hasName for a blog title and foaf:name for a person's name. aa:owner points from a blog to its owner. The location triples tell us which places the owners are recorded as being near.

@prefix :     <http://assaf.website/triples#> .@prefix aa:   <http://assaf.website/Personal#> .@prefix site: <http://assaf.website/> .@prefix ex:   <http://example.org/> .@prefix foaf: <http://xmlns.com/foaf/0.1/> .
site:blog aa:hasName "Ahmad Assaf's Blog" .site:blog aa:owner :ahmadassaf .:ahmadassaf foaf:name "Ahmad Assaf" .:ahmadassaf foaf:based_near ex:London .
ex:blog2 aa:hasName "Overfit.in" .ex:blog2 aa:owner ex:otherOwner .ex:otherOwner foaf:name "Other owner" .ex:otherOwner foaf:based_near ex:Manchester .

Finding Blog Names and Their Owners

First, find the blog titles. Then follow the ownership links to find the owners' names.

PREFIX aa: <http://assaf.website/Personal#>
SELECT ?nameWHERE { ?blog aa:hasName ?name .}

In the first query, aa:hasName is fixed. The terms beginning with a question mark are variables. Each of the two title triples supplies a blog and a name. Before we select a column to return, the bindings are:

?blog = http://assaf.website/blog, ?name = "Ahmad Assaf's Blog"?blog = http://example.org/blog2, ?name = "Overfit.in"

SELECT ?name returns the two titles. The pattern doesn't require a blog type. It finds any resource that has an aa:hasName value.

Chaining Queries: Getting Blog Owners' Names

The second query joins two patterns on ?owner. The first finds the owner IRI of each blog. The second uses that IRI as its subject and binds ?ownerName to the person's name.

The result will be two solution rows with the values Ahmad Assaf and Other owner because these are the only owners of the blogs in our RDF triples.

A property path describes a route through the graph. We can write aa:owner/foaf:name to follow the same two steps as the ownership query. The slash joins the steps through an intermediate resource without giving it a variable name. Keep the two separate patterns when you also want to return that resource, such as ?owner.

For a longer route, consider three hypothetical posts on Ahmad's blog. This small graph records direct hyperlinks between the posts. Run the following examples on this graph alone, with no reasoning enabled. The : prefix uses the same namespace as Ahmad's identifier, but these three IRIs identify posts.

@prefix :  <http://assaf.website/triples#> .@prefix aa: <http://assaf.website/Personal#> .
:modelingPost aa:linksTo :rdfPost .:rdfPost aa:linksTo :sparqlPost .

Which post can we reach from the modeling post by following exactly two hyperlinks?

PREFIX :  <http://assaf.website/triples#>PREFIX aa: <http://assaf.website/Personal#>
SELECT ?postWHERE { :modelingPost aa:linksTo/aa:linksTo ?post .}

The result is :sparqlPost. Each step matches one of the supplied triples. The query does not add a direct link from :modelingPost to :sparqlPost. Asking for that direct link with ASK { :modelingPost aa:linksTo :sparqlPost }, using the same prefixes, returns false on this graph. That answer means the direct triple has no match here; the actual page might contain a link we haven't recorded.

Replacing the path with aa:linksTo+ follows one or more links and returns both :rdfPost and :sparqlPost. With aa:linksTo*, zero steps are allowed too, so :modelingPost also appears. These forms find reachable endpoints; they do not return each intermediate route as a result column. SPARQL property paths

OWL, the Web Ontology Language, can express that a property is transitive: whenever A relates to B and B relates to C, A also relates to C. Declaring aa:linksTo transitive would therefore let an OWL reasoner infer a direct-link fact that these hyperlinks don't justify. Keep its meaning as a direct hyperlink and use the path expression for reachability. The modeling and reasoning post explains how such definitions affect query answers. OWL transitive properties

Counting Rows, Blogs, and Owners

Return to the original eight-triple directory. Its ownership query gave us two names, Ahmad Assaf and Other owner. We can keep that query's WHERE pattern and change the SELECT clause to count how many rows matched, how many blogs appeared in those rows, and how many owners they had.

PREFIX foaf: <http://xmlns.com/foaf/0.1/>PREFIX aa: <http://assaf.website/Personal#>
SELECT (COUNT(*) AS ?rows) (COUNT(DISTINCT ?blog) AS ?blogs) (COUNT(DISTINCT ?owner) AS ?owners)WHERE { ?blog aa:owner ?owner . ?owner foaf:name ?ownerName .}

This query returns one summary row. With our current data, ?rows, ?blogs, and ?owners are all 2. Each blog has a different owner IRI, and each owner has one name.

Suppose Ahmad Assaf owns both blogs. For this example, replace the ownership triple for blog2 with this one.

<http://example.org/blog2>  <http://assaf.website/Personal#owner> <http://assaf.website/triples#ahmadassaf> .

The WHERE pattern now matches these two rows. The table shortens the IRIs to their final parts for readability.

?blog?owner?ownerName
blog
ahmadassaf
Ahmad Assaf
blog2
ahmadassaf
Ahmad Assaf

If we select only ?ownerName, as in the earlier query, both rows display Ahmad Assaf. The repeated name comes from two different ownership triples, one for each blog. An RDF graph is a set of triples. SPARQL can return the same projected value for several matches.

The counting query returns these values in its summary row.

ExpressionWhat it countsResult
COUNT(*)
Matching solution rows
2
COUNT(DISTINCT ?blog)
Different blog IRIs in those rows
2
COUNT(DISTINCT ?owner)
Different owner IRIs in those rows
1

COUNT(?owner) would also return 2, because ?owner is bound in both rows. Adding DISTINCT inside the count means that owner IRI is counted once. W3C definition of COUNT

The name pattern affects the count, too. An owner without a foaf:name gives us no match. If Ahmad Assaf has two name values, each of his two blogs matches twice. That gives us four rows, still with two blog IRIs and one owner IRI.

Counting distinct names would count two people who share the same name only once. Counting owner IRIs avoids that, provided the data uses one IRI per person. If we have two IRIs for the same person, COUNT(DISTINCT ?owner) counts both.

To count blogs per owner, group the ownership matches by ?owner.

PREFIX aa: <http://assaf.website/Personal#>
SELECT ?owner (COUNT(DISTINCT ?blog) AS ?blogs)WHERE { ?blog aa:owner ?owner . }GROUP BY ?owner

The original directory gives two rows with one blog each. In the shared-owner variation, Ahmad has one row with two blogs. For the location query below, we return to the original directory.

Filtering by Location

Find the names of blog owners based near London.

PREFIX foaf: <http://xmlns.com/foaf/0.1/>PREFIX aa: <http://assaf.website/Personal#>
SELECT ?ownerNameWHERE { ?blog aa:owner ?owner . ?owner foaf:name ?ownerName . ?owner foaf:based_near <http://example.org/London> .}

The first two patterns find the owners and their names. The third keeps an owner only if the directory records foaf:based_near with <http://example.org/London> as its object.

The query returns one row, Ahmad Assaf. He is the only owner the directory records as based near London.

Query for Relationships

If you have a triple pattern in a query where the predicate is a variable, then you can explore the database to find relationships. For example, consider the query:

SELECT ?pWHERE {  <http://assaf.website/blog> ?p <http://assaf.website/triples#ahmadassaf> .}

The result is a single binding that reveals the relationship from Ahmad’s blog to Ahmad: the full IRI <http://assaf.website/Personal#owner>, which is what aa:owner abbreviates in the data.

Transform Data with CONSTRUCT

Suppose a reader needs ownership in the other direction, from each person to the blog they own. CONSTRUCT builds an RDF graph from the bindings in WHERE. Our template takes the owner and blog from each match and writes an inverse ownership triple.

PREFIX aa: <http://assaf.website/Personal#>
CONSTRUCT { ?owner aa:ownsBlog ?blog .}WHERE { ?blog aa:owner ?owner .}

The query returns these two triples. It leaves the input graph unchanged.

@prefix : <http://assaf.website/triples#> .@prefix aa: <http://assaf.website/Personal#> .@prefix ex: <http://example.org/> .
:ahmadassaf aa:ownsBlog <http://assaf.website/blog> .ex:otherOwner aa:ownsBlog ex:blog2 .

Using OPTIONAL

What happens if the directory hasn't recorded an owner's location? Try an isolated example with the same two people. Here, only Ahmad has a location.

@prefix : <http://assaf.website/triples#> .@prefix ex: <http://example.org/> .@prefix foaf: <http://xmlns.com/foaf/0.1/> .
:ahmadassaf foaf:name "Ahmad Assaf" ; foaf:based_near ex:London .ex:otherOwner foaf:name "Other owner" .

Both patterns are required, so only Ahmad's name has a match. RDF has no null term. If the directory hasn't supplied a location, there is simply no location triple to match. Making the location pattern OPTIONAL lets us retain both names:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?locWHERE { ?x foaf:name ?name . OPTIONAL {?x foaf:based_near ?loc .}}

The result has two rows. Ahmad's row binds both variables. The other row binds ?name to "Other owner" and leaves ?loc unbound.

Negation Using FILTER

Return to the original eight triples. Which blog owners have no location triple pointing to London? FILTER NOT EXISTS keeps a row when the pattern inside the braces has no match for that owner.

PREFIX foaf: <http://xmlns.com/foaf/0.1/>PREFIX aa: <http://assaf.website/Personal#>
SELECT ?nameWHERE { ?blog aa:owner ?x . ?x foaf:name ?name . FILTER NOT EXISTS { ?x foaf:based_near <http://example.org/London> . }}

The query returns Other owner. The directory records Manchester for that person and has no London match. If we remove the Manchester triple, the result stays the same. An absent London triple tells us what the directory has recorded. The person’s actual location could still be unknown. SPARQL negation

Negation in SPARQL 1.0

Negation in SPARQL 1.0 is weird. It is based on Negation as Failure and it is implemented using OPTIONAL, the bound filter, and the logical-not operator. The OPTIONAL block tries to match the pattern we want to exclude and binds a fresh variable (here ?london) only when it succeeds; the outer filter then keeps only the solutions where that variable stayed unbound. It is a bit convoluted, but it works and returns the same answer as the query above: Other owner.

PREFIX foaf: <http://xmlns.com/foaf/0.1/>PREFIX aa: <http://assaf.website/Personal#>
SELECT ?nameWHERE { ?blog aa:owner ?x . ?x foaf:name ?name . OPTIONAL { ?x foaf:based_near ?london . FILTER (?london = <http://example.org/London>) } FILTER (!bound(?london))}

Combining Data with UNION

PREFIX foaf: <http://xmlns.com/foaf/0.1/>PREFIX aa: <http://assaf.website/Personal#>
SELECT ?blogName ?personNameWHERE { ?blog aa:hasName ?blogName . { ?blog aa:owner ?person . } UNION { ?person aa:ownsBlog ?blog . } ?person foaf:name ?personName .}

The original directory matches only the aa:owner branch. The second branch works with data that expresses the inverse aa:ownsBlog relationship. It still needs the blog title and person name to complete the outer patterns. If a dataset contains both directions for the same ownership, both branches match and the projected row appears twice. Use SELECT DISTINCT if the result should contain each pair of names once.

Reading a named graph with GRAPH

An RDF dataset has one default graph and can contain named graphs. A query ordinarily matches its triple patterns against the default graph. GRAPH changes which graph a pattern reads. Suppose the directory keeps an accepted appointment date in its default graph and a source report in the named graph :reports85740. This small dataset is separate from the eight-triple directory above. In TriG syntax, the braces mark the contents of the named graph.

@prefix : <http://assaf.website/triples#> .@prefix aa: <http://assaf.website/Personal#> .@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
:appointment1 aa:startDate "2020-09-01"^^xsd:date .:reports85740 { :claim1 aa:aboutAppointment :appointment1 ; aa:reportedStartDate "2020-09-01"^^xsd:date .}
PREFIX : <http://assaf.website/triples#>PREFIX aa: <http://assaf.website/Personal#>
SELECT ?claim ?reported ?accepted WHERE { ?term aa:startDate ?accepted . GRAPH :reports85740 { ?claim aa:aboutAppointment ?term ; aa:reportedStartDate ?reported . }}

One row returns :claim1 and the date 2020-09-01 in both date columns. The shared ?term ties the report to the right appointment. To find reports in any named graph, replace GRAPH :reports85740 with GRAPH ?reportGraph and add ?reportGraph to SELECT. In this dataset the extra column contains :reports85740. SPARQL and RDF datasets

Beyond SELECT

The W3C chartered the SPARQL 1.1 working group in 2009 and published its Recommendations in 2013. Alongside COUNT, other aggregates give us a total (SUM), an average (AVG), or the smallest and largest values (MIN and MAX). The SPARQL 1.1 Query specification covers subqueries, which let one query use the results of another, and expressions that calculate values in the SELECT clause. It also explains how MINUS differs from the NOT EXISTS pattern we used for London. The W3C overview includes federation, which lets part of a query run against another SPARQL endpoint. For worked examples, I recommend Learning SPARQL.

Where I go next depends on what I need to do with the data.

  • To change the directory itself, SPARQL Update can insert or delete triples and create, clear, or drop a named graph.
  • If I have coordinates and want to ask how far an owner's recorded location is from London, GeoSPARQL provides spatial queries for distance, intersection, and containment.
  • For statements about triples, the W3C RDF & SPARQL Working Group publishes the RDF and SPARQL 1.2 specifications that grew out of RDF-star and SPARQL-star.
  • To query source files such as CSV, JSON, HTML, and spreadsheets, SPARQL Anything uses its Facade-X model to represent their contents as RDF containers and values. Enrico Daga, one of its developers, explains the approach in his talk on building knowledge graphs from these sources.

The opinions and views expressed on this blog are solely my own and do not reflect the opinions, views, or positions of my employer or any affiliated organizations. All content provided on this blog is for informational purposes only.

I'm glad to speak at events, join a panel or a podcast, or compare notes on AI, knowledge graphs and engineering leadership. Get in touch if you'd like to talk.