SPARQL Query Language for RDF

W3C Working Draft 17 February 2005

This version:
Previous version:
Latest version:
Eric Prud'hommeaux, W3C <eric@w3.org>
Andy Seaborne, Hewlett-Packard Laboratories, Bristol <andy.seaborne@hp.com>


RDF is a flexible, extensible way to represent information about World Wide Web resources. It is used to represent, among other things, personal information, social networks, metadata about digital artefacts, like music and images, as well as provide a means of integration over disparate sources of information. A standardized query language for RDF data with multiple implementations offers developers and end users a way to write and to consume the results of queries across this wide range of information. Used with a common protocol, applications can access and combine information from across the web.

This document describes the query language part of SPARQL Protocol And RDF Query Language for easy access to RDF stores. It is designed to meet the requirements and design objectives described in the W3C RDF Data Access Working Group (DAWG) document "RDF Data Access Use Cases and Requirements".

Status of This document

This is a second Public Working Draft of the Data Access SPARQL Query Language by the RDF Data Access Working Group (part of the Semantic Web Activity) for review by W3C Members and other interested parties. A change log shows the differences between this document and the previous version. It reflects the best effort of the editors to reflect implementation experience and incorporate input from various members of the WG, but is not yet endorsed by the WG as a whole. Editorial notes in "issue" style highlight issues or outstanding dissent. "todo" style indicates an area where the editors to provide more text. See the working group issues document for issues outside of this document. Please send comments to public-rdf-dawg-comments@w3.org, a mailing list with a public archive.

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced under the 5 February 2004 W3C Patent Policy. The Working Group maintains a public list of patent disclosures relevant to this document; that page also includes instructions for disclosing [and excluding] a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) with respect to this specification should disclose the information in accordance with section 6 of the W3C Patent Policy.

Per section 4 of the W3C Patent Policy, Working Group participants have 150 days from the title page date of this document to exclude essential claims from the W3C RF licensing requirements with respect to this document series. Exclusions are with respect to the exclusion reference document, defined by the W3C Patent Policy to be the latest version of a document in this series that is published no later than 90 days after the title page date of this document.

Table of Contents


See also:


DAWG issues list

1 Introduction

An RDF graph is a set of triples, each triple consisting of a subject, a predicate and an object, as defined in RDF Concepts and Abstract syntax. These triples can come from a variety of sources. For instance, they may come directly from an RDF document. They may be inferred from other RDF triples. They may be the RDF expression of data stored in other formats, such as XML or relational databases.

SPARQL  (SPARQL Protocol And RDF Query Language) is a query language for getting information from such RDF graphs. It provides facilities to:

As a data access language, it is suitable for both local and remote use. When used across networks, the companion SPARQL Protocol for RDF document [11] describes a remote access protocol.

1.1 Document Conventions

When undeclared, the namespace rdf stands in place of http://www.w3.org/1999/02/22-rdf-syntax-ns# , the namespace rdfs stands in place of http://www.w3.org/2000/01/rdf-schema#, and the namespace xsd for http://www.w3.org/2001/XMLSchema# .

2 Making Simple Queries

2.1 Writing a Simple Query

The example below shows a SPARQL query to find the title of a book from the information in an RDF graph. The query consists of two parts, the SELECT clause and the WHERE clause. The SELECT clause identifies the variables of interest to the application, and the WHERE clause has one triple pattern.

Data is in Turtle [15]. Examples will avoid using "a" and stick to rdf:type; also they will all be triples, not using ";" or ","


<http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> "SPARQL Tutorial" . 


SELECT ?title
WHERE  ( <http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> ?title )

Query Result:

"SPARQL Tutorial"

Query Term Syntax

This section is a fast introduction to the syntax.

The terms delimited by "<>" are URIs.

The query terms delimited by double quotes ("") are literals which, following N-Triples syntax [7], are a string, in quotes, an optional language tag, introduced with '@', or an optional datatype URIRef, introduced by '^^'.  Single quotes ('')  are also allowed. As a convenience, integers can be directly written and are interpreted as typed literals of datatype xsd:integer; floating point numbers can also be directly written and are interpreted as xsd:double.

Variables in SPARQL queries have global scope; it is the same variable everywhere in the query that the name is used. Variables are indicated by '?'; the '?' does not form part of the variable. '$' is an alternative to '?' to help where systems use '?' as a substitution character. In a query, $abc and ?abc are the same variable.

Because URIs can be long, SPARQL provides an abbreviation mechanism. Prefixes can be defined and a QName-like syntax [14] provides shorter forms: we also use the N3/Turtle [15] prefix mechanism for describing data. Prefixes apply to after they are defined. Redefining a prefix causes the new defintion to be used from that point in the syntax.

After parsing, URIs in queries are always absolute URIs.  The term "URI" in this document should be read as "absolute URI".

Triple Patterns (definition link) are written as a list of subject predicate object inside round brackets.

Examples of Query Syntax

PREFIX  dc: <http://purl.org/dc/elements/1.1/>
SELECT  ?title
WHERE   ( <http://example.org/book/book1> dc:title ?title )
PREFIX  dc: <http://purl.org/dc/elements/1.1/>
PREFIX  : <http://example.org/book/>
SELECT  $title
WHERE   ( :book1  dc:title  $title )

Data descriptions used in this document

Defer to Turtle.

Similarly, we abbreviate data with Turtle-style prefixes:

@prefix dc:   <http://purl.org/dc/elements/1.1/> .
@prefix :     <http://example.org/book/> .
:book1  dc:title  "SPARQL Tutorial" .

Prefixes are syntactic: the prefix name does not effect the query, nor do prefix names in queries need to be the same prefixes as used for data. This query is equivalent to the previous one and will give the same results when applied to the same graph.

PREFIX  dcore:  <http://purl.org/dc/elements/1.1/>
SELECT  ?title
WHERE   ( ?book dcore:title ?title )

Result Descriptions used in this document

The term "binding" is used as a descriptive term to refer to a pair of variable and RDF term. In this document, we illustrate bindings in results in tabular form so if variable x is bound to "Alice" and variable y is bound to "Bob", we show this as:

x y
"Alice" "Bob"

Not every binding needs to exist in every row of the table. Optional matches and alternative matches may leave some variables unbound (see the bound test).

Results can be returned in RDF, in XML the SPARQL Variable Binding Results XML Format [16] and also in forms specific to implementation APIs.

2.2 Graph Patterns

The building blocks of queries are triple patterns. Syntactically, a SPARQL triple pattern is a subject, predicate and object delimited by parentheses. The example in section 2.1 shows a triple pattern with a subject variable (the variable book), a predicate of dc:title and an object variable (the variable title).

( ?book dc:title ?title )

Matching a triple pattern to a graph, gives bindings between variables and RDF Terms so that the triple pattern, with the variables replaced by the corresponding RDF terms, is a triple of the graph being matched.

Definition: RDF Term

An RDF Term is anything that can occur in the RDF data model.
let RDF-U be the set of all RDF URIs
let RDF-L be the set of all RDF Literals
let RDF-B be the set of all bNodes

The set of RDF Terms, RDF-T, is RDF-U union RDF-L union RDF-B.

Definition: RDF Ground Term

The set of RDF Ground Terms, RDF-G, is the set of RDF terms that are not a bNodes. RDF-G is RDF-U union RDF-L.

Definition: Query Variable

Let V be the set of all query variables. V and RDF-T are disjoint.

An RDF triple contains three components:

In SPARQL, a triple pattern is similar to an RDF triple but with the addition that components can be a query variable.

Definition: Triple Pattern

The set of triple patterns is
    (RDF-G union V) x (RDF-U union V) x (RDF-G union V)

This definition of Triple Pattern includes literal subjects. This has been noted by RDF-core.

"noted that it is aware of no reason why literals should not
  be subjects and a future WG with a less restrictive charter may
  extend the syntaxes to allow literals as the subjects of statements."

Definition: Basic Pattern

A basic pattern is a set of Triple Patterns.

An RDF graph is a set of RDF triples.  In the same way, a SPARQL Basic Pattern is a set of Triple Patterns.

Definition: Query Pattern

A query has one main graph pattern.  It is called the Query Pattern.

2.3 Graph Pattern Matching

Definition: Substitution

Substitution is a function from a subset of the set of variables, V, the domain of the substitution, dom(S), to the set of RDF terms, T.

Definition: Restriction

If X is a subset of dom(S) and dom(S')=X and S'(v) = S(v) for all v in X then S' is the restriction of S to X, written S|X.

Definition: Pattern Instance

If S is a substitution then the result of replacing any v in a basic pattern P by S(v) is a pattern instance of P, written S(P).

For example, the query:

SELECT ?x ?v WHERE ( ?x ?x ?v )

has a single triple patten as the query pattern. It matches a graph of a single triple:

rdf:type rdf:type rdf:Property .

with substitution:

x v
rdf:type rdf:Property

It does not match the graph of a single triple:

rdfs:seeAlso rdf:type rdf:Property .

because the variable x would need to be both rdfs:seeAlso and rdf:type.

Definition: Pattern Solution

A Pattern Solution of Graph Pattern GP on graph G is any substitution S such that S(GP) is a subgraph of G.

Where it is clear, a pattern solution is simply called a solution.

2.4 Examples of Graph Patterns

The keyword WHERE is followed by a Graph Pattern, called the Query Pattern. The simplest form of Graph Pattern is the Triple Pattern. More complex patterns can be created by combining patterns in various ways. One of these is the Basic Pattern. The other operators are for Optional Patterns[@link@], Alternate Patterns [@link], and an operator that provides access to source information [@link@].

In the basic pattern, for the pattern to match, there must be a substitution where each of the tripe patterns matches with the same substiution.


@prefix foaf:    <http://xmlns.com/foaf/0.1/> .

_:a  foaf:name   "Johnny Lee Outlaw" .
_:a  foaf:mbox   <mailto:jlow@example.com> .

There is a bNode [12] in this dataset, identified by _:a. The label is only used within the file for encoding purposes. The label information is not in the RDF graph. No SPARQL query will be able to identify that bNode by the label used in the serialization.


PREFIX foaf:   <http://xmlns.com/foaf/0.1/> 
SELECT ?mbox
  ( ?x foaf:name "Johnny Lee Outlaw" )
  ( ?x foaf:mbox ?mbox )

Query Result:


This query contains a basic graph pattern of two triple patterns, each of which must match for the graph pattern to match.

2.5 Multiple Matches

The results of a query are all the ways a query can match the graph being queried. Each result is one solution to the query and there may be zero, one or multiple results to a query, depending on the data.

Definition: Query Solution

A Query Solution is a Pattern Solution for the Query Pattern. A substitution in a query solution only contains variables mentioned in the query.

Definition: Query Results

The Query Results, for a given graph pattern GP on graph G, is written R(GP,G), and is the set of all query solutions S such that S is a solution for GP on G.

R(GP, G) may be the empty set.


@prefix foaf:  <http://xmlns.com/foaf/0.1/> .

_:a  foaf:name   "Johnny Lee Outlaw" .
_:a  foaf:mbox   <mailto:jlow@example.com> .
_:b  foaf:name   "Peter Goodguy" .
_:b  foaf:mbox   <mailto:peter@example.org> .


PREFIX foaf:   <http://xmlns.com/foaf/0.1/> 
SELECT ?name ?mbox
  ( ?x foaf:name ?name )
  ( ?x foaf:mbox ?mbox )

Query Result:

name mbox
"Johnny Lee Outlaw" <mailto:jlow@example.com>
"Peter Goodguy" <mailto:peter@example.org>

The results enumerate the RDF terms to which the selected variables can be bound in the query pattern. In the above example, the following two subsets of the data caused the two matches.

 _:a foaf:name  "Johnny Lee Outlaw" .
 _:a foaf:box   <mailto:jlow@example.com> .
 _:b foaf:name  "Peter Goodguy" .
 _:b foaf:box   <mailto:peter@example.org> .

For a simple, conjunctive graph pattern match, all the variables used in the query pattern will be bound in every solution.

2.5 Blank Nodes

Blank Nodes and Queries

BNodes can't appear in a SPARQL query patterns.

Blank Nodes and Results

In the results of queries, the presence of bNodes can be indicated by labels in the serializations of results but the labels can be relabelled on 1:1 basis. An appliction or client receiving the results of a query can tell that two solutions to a query differ in bNodes but this information is only scoped to the results (result set or RDF graph) as defined in "SPARQL Variable Binding Results XML Format"


@prefix foaf:  <http://xmlns.com/foaf/0.1/> .

_:a  foaf:name   "Alice" .
_:b  foaf:name   "Bob" .


PREFIX foaf:   <http://xmlns.com/foaf/0.1/> 
SELECT ?x ?name
WHERE  ( ?x foaf:name ?name )
x name
_:c "Alice"
_:d "Bob"

The results above could equally be given with different bNode labels because the labels in the results only indicate whether RDF terms in the solutions were the same or different.

x name
_:r "Alice"
_:s "Bob"

These two results have the same information: the blank node used to match the query was different in the two solutions.  There is no relation between using _:a in the results and any internal blank node label in the data graph; the labels in the results only indicate whether RDF terms in the solutions were the same or different.

3 Working with RDF Literals

An RDF Literal is written in SPARQL as string containing the lexical form of the literal, delimited by "", follwoed by an optional language tag (indicted by '@') or optional datatype (indicated by '^^').  There are convenience forms for numeric-types literals which are xsd:integers and xsd:doubles.

Examples of literal syntax in SPARQL:

3.1 Matching RDF Literals

The dataset below contains a number of RDF literals:

@prefix dt:   <http://example.org/datatype#> .
@prefix ns:   <http://example.org/ns#> .
@prefix :     <http://example.org/ns#> .
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> .

:x   ns:p     "42"^^xsd:integer .
:x   ns:p     "abc"^^dt:specialDatatype .
:x   ns:p     "cat"@en .

Matching Integers

The pattern in the following query has a solution because 42 is syntax for "42"^^http://www.w3.org/2001/XMLSchema#integer.

SELECT ?v WHERE (?v ?p 42) 

Matching Arbitrary Datatypes

The following query has a solution: note that the query processor does not have to have any understanding of the values in the space of the datatype.

SELECT ?v WHERE ( ?x ?p "abc"^^<http://example.org/datatype#specialDatatype> )

Matching Language Tags

This following query has no solution because "cat" is not the same RDF literal as "cat"@en:

SELECT ?v WHERE ( ?x ?p "cat" )

but this does find a solution:

SELECT ?v WHERE ( ?x ?p "cat"@en )

3.2 Constraining Values

Graph pattern matching creates bindings of variables. It is possible to further restrict possible solutions by constraining the allowable binding of variables to RDF Terms.  Constraints in SPARQL take the form of boolean-valued expressions; the language also allows application-specific constraints on the values in a query solution.


@prefix dc:   <http://purl.org/dc/elements/1.1/> .
@prefix :     <http://example.org/book/> .
@prefix ns:   <http://example.org/ns#> .

:book1  dc:title  "SPARQL Tutorial" . 
:book1  ns:price  42 .
:book2  dc:title  "The Semantic Web" . 
:book2  ns:price  23 .


PREFIX  dc:  <http://purl.org/dc/elements/1.1/>
PREFIX  ns:  <http://example.org/ns#> 
SELECT  ?title ?price
WHERE   ( ?x dc:title ?title )
        ( ?x ns:price ?price ) AND ?price < 30

Query Result:

title price
"The Semantic Web" 23

By having a constraint on the "price" variable, only one of the books matches the query because there is a restriction on the allowable values of "price".

Definition: Constraints

A patten may be a constraint is a boolean-valued expression of variables and RDF Terms that can be applied to restrict query solutions.

Solutions are required to bind variables occurring in constraints to typed literals such that the constraint is true when applied to the value of the typed literal. In this way, patterns may constrain literals to have particular values rather than having particular syntactic forms. Note that a constraint can be considered to be a triple with a special predicate.

SPARQL defines a set of functions & operations (sections 11.1 and 11.2) that all implementations must provide. In addition, there is an extension mechanism (section 11.3) for boolean tests that are specific to an application domain or kind of data.

A constraint may lead to an error condition when testing some variable binding.  The exact error will depend on the constraint: in numeric operations, solutions with variables bound to a non-number or a bNode will lead to such  an error.  Any potential solution that causes an error condition in a constraint will not form part of the final results.

4 Combining Patterns

Complex graph patterns can be made by combining simpler patterns. The ways of creating patterns from triple patterns are:

A group of patterns is delimited with {}s (that is, braces).

Definition: Graph Pattern – Grouping

A graph pattern GP may be a set of graph patterns, GPi.and set of constraints Cj. A solution of Graph Pattern GP on graph G is any solution S such that for each element GPi of GP, S is a solution of GPi and each constraint Cj is true.

For any solution, the same variable is given the same value everywhere in the set of graph patterns. A Basic Graph Patterns is, as described above, is a group of triple patterns. For example, this query has a group pattern of one basic pattern as the query pattern.

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
         ( ?x foaf:name ?name )
         ( ?x foaf:mbox ?mbox )
The same solutions would be obtained from a query that grouped the patterns as below:
PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE  ( ?x foaf:name ?name )
       { ( ?x foaf:mbox ?mbox ) }

and because solutions to a group is a solution to each element of a group and a solution of a basic pattern is a solution to each triple pattern, these queries also have the same solutions as:

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE  ( ?x foaf:name ?name ) ( ?x foaf:mbox ?mbox )

5 Including Optional Values

Basic patterns and value constraints allow queries to perform quieres where al the part of the query pattern must match for there to be a solution. For every solution of the query, every variable is bound to an RDF Term in a pattern solution. RDF is semistructured so a regular structure can not be assumed and so it is useful to be able to have queries that allow information to be added to solution where the information is available, but where the solution is not returned just beause that part of the query pattern does not match. Optional matching provides this facility; if teh optional part does not lead to any solutions, variables can be left unbound.

5.1 Optional Pattern Matching

Optional parts of the graph pattern may be specified syntactically with the OPTIONAL keyword on either a triple or graph pattern:

OPTIONAL (?s ?p ?o)
OPTIONAL { (?s ?p ?o) }


@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  rdf:type        foaf:Person .
_:a  foaf:name       "Alice" .
_:a  foaf:mbox       <mailto:alice@work.example> .

_:b  rdf:type        foaf:Person .
_:b  foaf:name       "Bob" .
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE  ( ?x foaf:name  ?name )
       OPTIONAL ( ?x  foaf:mbox  ?mbox ) 

With the data above, the query result is:

name mbox
"Alice" <mailto:alice@example.com>

There is no value of mbox in the solution where the name is "Bob". It is left unset.

This query finds the names of people in the data, and, if there is a triple with predicate mbox and same subject, retrieves the object of that triple as well. In the example, only a single triple pattern is given in the optional match part of the query but in general it is any graph pattern.

The whole graph pattern of an optional block must match for the optional to add to the query solution.

5.2 Constraints in Optional Blocks

Constraints can be given in optional blocks as this examples shows:

@prefix dc:   <http://purl.org/dc/elements/1.1/> .
@prefix :     <http://example.org/book/> .
@prefix ns:   <http://example.org/ns#> .

:book1  dc:title  "SPARQL Tutorial" . 
:book1  ns:price  42 .
:book2  dc:title  "The Semantic Web" . 
:book2  ns:price  23 .
PREFIX  dc:  <http://purl.org/dc/elements/1.1/>
PREFIX  ns:  <http://example.org/ns#> 
SELECT  ?title ?price
WHERE   ( ?x dc:title ?title )
        OPTIONAL { ( ?x ns:price ?price ) AND ?price < 30 }
title price
"SPARQL Tutorial"  
"The Semantic Web" 23

No price appears for the book with title "SPARQL Tutorial" because the optional block did not lead to a solution involving variable price.

5.3 Multiple Optional Blocks

Query patterns are defined recursively.  A query may have zero or more optional blocks and any part fo a query may have an optional part.


@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  foaf:name       "Alice" .
_:a  foaf:homepage   <http://work.example.org/alice/> .

_:b  foaf:name       "Bob" .
_:b  foaf:mbox       <mailto:bob@work.example> .


PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox ?hpage
WHERE  ( ?x foaf:name  ?name )
       OPTIONAL ( ?x foaf:mbox ?mbox )
       OPTIONAL ( ?x foaf:homepage ?hpage )

Query result:

name mbox hpage
"Alice" <http://work.example.org/alice/>
"Bob" <mailto:bob@example.com>

In this example, there are two independent optional blocks. Each depends only on variables defined in the non-optional part of the graph pattern. If a new variable is mentioned in an optional block (as mbox and hpage are mentioned in the previous example), that variable can be mentioned in that block and can not be mentioned in a subsequent block.

5.4 Optional Matching – Formal Definition

In an optional match, either a graph pattern matches a graph and so defines one or more pattern solutions, or gives an empty pattern solution but does not cause matching to fail overall.

Definition: Optional Matching

Given graph pattern GP1, and graph pattern GP2, let GP= (GP1 union GP2).

The optional match of GP2 of graph G, given GP1, defines a pattern solution PS such that:

If GP matches G, then the solutions of GP is the patterns solutions of GP else the solutions are the pattern solutions of GP1 matching G.

5.5 Nested Optional Blocks

Optional patterns can occur inside any pattern, including another optional pattern, forming a nested pattern. The outer optional block must match for any nested one to be matched.


@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .
@prefix vcard:      <http://www.w3.org/2001/vcard-rdf/3.0#> .
_:a  foaf:name     "Alice" .
_:a  foaf:mbox     <mailto:alice@work.example> .
_:a  vcard:N       _:x .

_:x  vcard:Family  "Hacker" .
_:x  vcard:Given   "Alice" .

_:b  foaf:name     "Bob" .
_:b  foaf:mbox     <mailto:bob@work.example> .
_:b  foaf:N        _:z .

_:z  vcard:Family  "Hacker" .

_:e  foaf:name     "Ella" .
_:e  vcard:N       _:y .

_:y  vcard:Given   "Eleanor" .


PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#>
SELECT ?foafName ?gname ?fname
      ( ?x foaf:name ?foafName )

      OPTIONAL ( ?x foaf:mbox ?mbox ) 

      OPTIONAL { ( ?x vcard:N ?vc )
                 ( ?vc vcard:Given ?gname )
                 OPTIONAL ( ?vc vcard:Family ?fname )

Query result:

foafName mbox gname fname
"Alice" <mailto:alice@work.example> "Alice" "Hacker"
"Bob"  <mailto:bob@work.example>
"Ella"   "Eleanor"  

This query finds the name, optionally the mbox, and also the vCard given name; further, if there is a vCard Family name as well as the Given name, the query gets that as well.

By nesting the optional access to vcard:Family, the query only reaches these if there is a vcard:N predicate. It is possible to expand out optional blocks to remove nesting at the cost of duplication of expressions. Here, the expression is a simple triple pattern on vcard:N but it could be a complex graph match with value constraints.

5.6 Requirements for Nested Optional Patterns

There is an additional condition that must be met for nested optional blocks. Considering the graph pattern as a tree of blocks, then a variable in an optional block can only be mentioned in other optional blocks nested within it (or in the SELECT clause). A variable can not be used in two optional blocks where the outermost mention (shallowest occurrence in the tree for each occurrence) of the two uses is not the same block.

For each variable v that occurs in a nested block, consider all paths from that variable in any block to the root of the tree. Those paths must all intersect at a block that also contains the variable v.

The purpose of this condition is to enable the query processor to process the query blocks in arbitrary (or optimized) order. If a variable was introduced in one optional block and mentioned in another, it would be used to constrain the second. Reversing the order of the optional blocks would reverse the blocks in which the variable was introduced and was used to constrain. Such a query could give different results depending on the order in which those blocks were evaluated.

6 More Pattern Matching – Alternatives

SPARQL provides a means combining graph patterns so that one of several alternative graph patterns may match.  If more than one of the alternatives matches, all the possible pattern solutions are found.

6.1 Joining Patterns with UNION

The UNION keyword is the syntax for pattern alternatives.


@prefix dc10:  <http://purl.org/dc/elements/1.0/> .
@prefix dc11:  <http://purl.org/dc/elements/1.1/> .

_:a  dc10:title     "SPARQL Query Language Tutorial" .
_:a  dc10:creator   "Alice" .

_:b  dc11:title     "SPARQL Protocol Tutorial" .
_:b  dc11:creator   "Bob" .


PREFIX dc10:  <http://purl.org/dc/elements/1.1/>
PREFIX dc11:  <http://purl.org/dc/elements/1.0/>

SELECT ?title
WHERE  ( ?book dc10:title  ?title ) UNION ( ?book dc11:title  ?title )

Query result:

"SPARQL Protocol Tutorial"
"SPARQL Query Language Tutorial"

This query finds titles of the books in the dataset, whether the title is recorded using Dublin Core properties from version 1.0 or version 1.1. If the application wishes to know how exactly the information was recorded, then the query:

PREFIX dc10:  <http://purl.org/dc/elements/1.1/>
PREFIX dc11:  <http://purl.org/dc/elements/1.0/>

SELECT ?x ?y
WHERE  ( ?book dc10:title ?x ) UNION ( ?book dc11:title  ?y )
x y
  "SPARQL Protocol Tutorial"
"SPARQL Query Language Tutorial"  

will return results with the variables x or y bound depending on which way the query processor matches the pattern to the dataset. Note that, unlike optionals, if neither part of the UNION pattern matched, then the query pattern would not match.

6.2 Blocks in UNION Patterns

More than one triple pattern can be given in each alternative possibility:

PREFIX dc10:  <http://purl.org/dc/elements/1.1/>
PREFIX dc11:  <http://purl.org/dc/elements/1.0/>

SELECT ?title ?author
WHERE  { ( ?book dc10:title ?title )  ( ?book dc10:creator ?author ) }
       { ( ?book dc11:title ?title )  ( ?book dc11:creator ?author ) }
author title
"Alice" "SPARQL Protocol Tutorial"
"Bob" "SPARQL Query Language Tutorial"

This query will only match a book if it has both a title and creator predicate from the same version of Dublin Core.

6.3 Alternative Matching – Formal Definition

Definition: Pattern Matching (Disjunction)

Given graph patterns GP1 and GP2, and graph G,  then a disjunction pattern solution of GP1 and GP2 is any pattern solution S such that either S(GP1) matches G or S(GP2) matches G with substitution S.

Query results involving a pattern containing GP1 and GP2, will include separate solutions for each match where GP1 and GP2 give rise to different sets of bindings.

7 RDF Dataset

The RDF data model expresses information as a graph comprising of triples with subject, predicate and object.  Many RDF data stores hold a multiple RDF graphs, and record information about each graph, allowing an application to make queries that involve information from more than one graph.

A SPARQL query is made against an RDF Dataset which represents such a collection of graphs. Different parts of the query are matched against different graphs as described in the next section. There is one graph which does not have a name, called the background graph, and zero or more named graphs, identified by URI reference.

Definition: RDF Dataset

An RDF dataset is a set = { G, (u1, G1), (u2, G2), . . . (un, Gn) } where G and each Gi are graphs, and each ui is a URI. Each ui is distinct.

G is a called the background graph. Gi are named graphs.

In the previous sections, all queries have been shown executed against the single, background graph. A query does not need to involve the background graph; the query can just involve the named graphs.

"Querying the Dataset" describes how queries access the different parts of the RDF dataset.

"Specifying the RDF Dataset" describes how a query can specify the dataset.

The RDF dataset does not need to described in the query.  It can be given implicitly by the local API, externally from the SPARQL protocol as well specified in the query itself as described in section "Specifying the RDF Dataset".

A query processor is not required to support named graphs.

8 Querying the Dataset

When querying a collection of graphs, the GRAPH keyword allows access to the URIs naming the graphs in the RDF Dataset, or allows restriction a graph pattern to be applied to a specific named graph.

The following two graphs will be used in examples:

# Graph: http://example.org/foaf/aliceFoaf
@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a  foaf:name     "Alice" .
_:a  foaf:mbox     <mailto:alice@work.example> .
_:a  foaf:knows    _:b .

_:b  foaf:name     "Bob" .
_:b  foaf:mbox     <mailto:bob@work.example> .
_:b  foaf:age      32 .
_:b  foaf:PersonalProfileDocument <http://example.org/foaf/bobFoaf> .
# Graph: http://example.org/foaf/bobFoaf
@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:1  foaf:mbox     <mailto:bob@work.example> .
_:1  foaf:PersonalProfileDocument <http://example.org/foaf/bobFoaf>.
_:1  foaf:age 35 .

8.1 Accessing Graph Labels

Access to the graph labels of the collection of graphs being queried is by variable in the GRAPH expression.

The query below matches the pattern on each of the named graphs in the dataset and forms solutions which have the src variable bound to URIs of the graph being matched. The pattern part of the GRAPH only matched triples in a single named graph in the same way that a graph pattern matches the background graph when there is no GRAPH clause being applied.

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX data: <http://example.org/foaf/>

SELECT ?src ?bobAge
  GRAPH ?src
    ( ?x foaf:mbox <mailto:bob@work.example> )
    ( ?x foaf:age ?bobAgge )

The query result gives the label of the graphs where the information was found and the value for Bob's age:

src bobAge
<http://example.org/foaf/aliceFoaf> 32
<http://example.org/foaf/bobFoaf> 35

It is not necessary to use the GRAPH clause to create the data graph for a collection of graphs. The query environment may provide the RDF dataset to be queried.

8.2 Restricting by Graph Label

The query can restrict the matching applied to a specific graph by supplying the graph label.  This query looks for the age as the graph http://example.org/foaf/bobFoaf asserts it.

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX data: <http://example.org/foaf/>

    GRAPH data:bobFoaf {
        ( ?x foaf:mbox <mailto:bob@work.example> )
        ( ?x foaf:age ?age )

which yields a single solution:


8.3 Restricting via Query Pattern

A variable used in the GRAPH clause may also be used elsewhere in the query, whether in about GRAPH clause or in a graph pattern matched against the background graph in the dataset.

This can be used to find information in one part of a querym, and using it to restrict the graphs matched in another part of the query. The query below uses the graph with URI http://example.org/foaf/aliceFoaf to find the profile document for Bob; it then matches another pattern against that graph. Note that the pattern in the second GRAPH part finds the bNode for the person with the same mail box (given by variable mbox) as foudn in the first GRAPH part, because the bNode used to match for variable whom from Alice's FOAF file is not the same bNode in the profile document.

PREFIX data: <http://example.org/foaf/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT ?mbox ?age ?ppd
  GRAPH data:aliceFoaf
    ( ?alice foaf:mbox <mailto:alice@work.example> )
    ( ?alice foaf:knows ?whom )
    ( ?whom foaf:mbox ?mbox )
    ( ?whom PersonalProfileDocument  ?ppd )
  GRAPH ?ppd
     ( ?w foaf:mbox ?mbox )
     ( ?w foaf:age ?age )
mbox age ppd
<mailto:bob@work.example> 35 <http://example.org/foaf/bobFoaf>

Any  triple in Alice's FOAF file giving Bob's age is not used to provide an age for Bob because the pattern involving variable age is restricted by ppd to a particualr Personal Profile Document.

8.4 GRAPH and a background graph

Query patterns can involve both the background graph and the named graphs. In this example, a aggregator has found read in a web resource on two different occasions.  Each time a graph is read into the aggregator, it is given a URI by the local system. The graphs are nearly the same but the email address for "Bob" has changed.

The default graph is being used to record the provenance information and the RDF data actually read is kept in two separate graphs, each of which is given a different URI by the system. The RDF dataset consists of two, named graphs and the information about them.

RDF Dataset:

# Background graph
@prefix dc: <http://purl.org/dc/elements/1.1/> .

<urn:x-local:graph1> dc:publisher "Bob" .
<urn:x-local:graph1> dc:date "2004-12-06"^^xsd:date .

<urn:x-local:graph2> dc:publisher "Bob" .
<urn:x-local:graph2> dc:date "2005-01-10"^^xsd:date .
# Graph: urn:x-local:graph1
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

_:a foaf:name "Alice" .
_:a foaf:mbox <mailto:alice@work.example> .

_:b foaf:name "Bob" .
_:b foaf:mbox <mailto:bob@oldcorp.example.org> .
# Graph: urn:x-local:graph2
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

_:a foaf:name "Alice" .
_:a foaf:mbox <mailto:alice@work.example> .

_:b foaf:name "Bob" .
_:b foaf:mbox <mailto:bob@newcorp.example.org> .

This query finds email addresses, detailing the name of the person and the date the information was discovered.

PREFIX data: <urn:x-local:>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
Prefix dc: <http://purl.org/dc/elements/1.1/>

SELECT ?name ?mbox ?date
    ( ?g dc:publisher ?name)
    ( ?g dc:date ?date )
    GRAPH ?g 
      ( ?person foaf:name ?name )
      ( ?person foaf:mbox ?mbox )
The results show that "Bob" email address has changed.
name mbox date
"Bob" <mailto:bob@oldcorp.example.org> "2004-12-06"^^xsd:date
"Bob" <mailto:bob@newcorp.example.org> "2005-01-10"^^xsd:date

The URI for the date data type has been abbreviated in the results just for convenience.

8.5 Definition for GRAPH

Definition: DatatSet Graph Pattern

If D is a dataset {G, (<u1> G1), ...}, and P is a graph pattern then S is a pattern solution of GRAPH(g, P) if:

g is a URI where g = <ui> for some i, and S is pattern solution of P on Gi or g is a variable, S contains the binding var = <ui> and S is a pattern solution of P on Gi.

9 Specifing RDF Datasets

The WITH clause gives URIs that the query processor can use to create the background graph and the FROM clause can be used to specify named graphs. A query processor may use these URIs in any way to associate an RDF Dataset with a query. For example, it could use URIs to retrieve documents, parse them and use the resulting triples as one of the graphs; alternatively, it might only service queries that specify URIs of graphs that it already has stored.

9.1 Specifying the Background Graph

The WITH clause supplies a list of URIs that can be used to establish one background graph. A query processor may use the URIs to create a new graph or require that there is a single URI to identify one of a fixed set of graphs that the query processor is able to apply a query to

In this first example, there is a single graph that is identified in the query:

# Graph: http://example.org/foaf/aliceFoaf
@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a  foaf:name     "Alice" .
_:a  foaf:mbox     <mailto:alice@work.example> .
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT  ?name
WITH    <http://example.org/foaf/aliceFoaf>
WHERE   (?x foaf:name ?name)

The query processor uses the URI to build an RDF dataset with one background graph.

Some processors may choose to allow multiple URIs in the WITH clause.  These are used to create a single graph by RDF merge.

# Graph: http://example.org/foaf/graph1
@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a1  foaf:knows    _:b .
_:a1  foaf:name     "Alice" .

_:b1  foaf:name     "Bob" .
# Graph: http://example.org/foaf/graph2
@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a2  foaf:knows    _:e .

_:b2  foaf:name     "Bob" .
_:b2  foaf:knows    _:e .

_:e   foaf:name     "Eve" .
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?xName ?yName
WITH <http://example.org/foaf/graph1> <http://example.org/foaf/graph2> 
WHERE   (?x foaf:knows ?y)
        (?x foaf:name  ?xName)
        (?y foaf:name  ?yName)
xName yName
"Alice" "Bob"
"Bob" "Eve"

In an RDF merge, bNodes from each graph being merged are kept separate so the lack of a foaf:name triple for "Alice" in graph2 means that there is no solution with xName bound to "Alice" and yName bound to "Eve".

URIs can be abbreviated using the PREFIX mechanism:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX data: <http://example.org/foaf/>
SELECT  ?xName ?yName
WITH    data:graph1 data:graph2
WHERE   (?x foaf:knows ?y)
        (?x foaf:name  ?xName)
        (?y foaf:name  ?yName)

9.2 Specifying Named Graphs

A query can supply a list URIs for the named graphs in the RDF Dataset using the FROM clause.  Each URI in the list is used to provide one, named graph in the RDF Dataset.

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?src ?name
FROM   <http://example.org/foaf/graph1> <http://example.org/foaf/graph2> 
    GRAPH ?src ( ?x foaf:name ?name)

The GRAPH keyword is the mechanism by which a query directs graph patterns to be matched against named graphs and is described in the section "Accessing Graph Labels"

9.3 Combining WITH and FROM

The WITH clause and FROM clause can be used in the same query. Some of the RDF Dataset can also be supplied by the query processor, so, for example, the background graph may be supplied even if the query does not provide a WITH clause.

One way of identifying the RDF Dataset for a query execution is by the SPARQL protocol.

-- example from 8.3 --

PREFIX data: <urn:x-local:>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
Prefix dc: <http://purl.org/dc/elements/1.1/>

SELECT ?name ?mbox ?date
WITH   data:details
FROM   data:graph1  data:graph2
    ( ?g dc:publisher ?name)
    ( ?g dc:date ?date )
    GRAPH ?g 
      ( ?person foaf:name ?name )
      ( ?person foaf:mbox ?mbox )

10 Result Forms

SPARQL has a number of query forms for returning results. These result forms use the solutions from pattern matching the query pattern to form result sets or RDF graphs. A result set is a serialization of the bindings in a query result. The query forms are:

Returns all, or a subset of, the variables bound in a query pattern match. Formats for the result set can be in XML or RDF/XML (see the result format document)
Returns either an RDF graph that provides matches for all the query results or an RDF graph constructed by substituting variables in a set of triple templates.
Returns an RDF graph that describes the resources found.
Returns whether a query pattern matches or not.

10.1 Selecting which Variables to Return

The SELECT form of results returns the variables directly. The syntax SELECT * is shorthand for select all the variables.

@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a    foaf:name   "Alice" .
_:a    foaf:knows  _:b .
_:a    foaf:knows  _:c .

_:b    foaf:name   "Bob" .

_:c    foaf:name   "Clare" .
_:c    foaf:nick   "CT" .

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT ?nameX ?nameY ?nickY
     ( ?x foaf:knows ?y    )
     ( ?x foaf:name ?nameX )
     ( ?y foaf:name ?nameY )
     OPTIONAL ( ?y foaf:nick ?nickY )
nameX nameY nickY
"Alice" "Bob"  
"Alice" "Clare" "CT"

Result sets can be accessed by the local API but also can be serialized into either XML or an RDF graph. The XML result set form gives:

<?xml version="1.0"?>
  xmlns="http://www.w3.org/2001/sw/DataAccess/rf1/result" >
    <variable name="nameX"/>
    <variable name="nameY"/>
    <variable name="nickY"/>
      <nickY bound="false"/>

And in RDF/XML, using the Variable Binding Results XML Format [16] gives:


    <rs:solution rdf:parseType="Resource">
      <rs:binding rdf:parseType="Resource">
      <rs:binding rdf:parseType="Resource">
      <rs:binding rdf:parseType="Resource">
   <rs:solution rdf:parseType="Resource">
      <rs:binding rdf:parseType="Resource">
      <rs:binding rdf:parseType="Resource">

Results can be thought of as a table, with one row per query solution. Some cells may be empty because a variable is not bound in that particular solution.

Implementations may return solutions as eother a bag or set, that is, with ot without duplicate rows.  However, if the DISTINCT keyword is specificed, a set of results must be returned, with no duplicates.


The result set can be restricted by adding the DISTINCT keyword which ensures that every combination of variable bindings (i.e. each result) in a result set must be unique. Thought of as a table, each row is different.

@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a    foaf:name   "Alice" .
_:a    foaf:mbox   <mailto:alice@org> .

_:z    foaf:name   "Alice" .
_:z    foaf:mbox   <mailto:smith@work> .
PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
SELECT DISTINCT ?name WHERE ( ?x foaf:name ?name )


The LIMIT form puts an upper bound on the number of solutions returned. A query may return a number of results up to and including the limit. If the number of actual solutions is less than the limit, all solutions will be returned.

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

SELECT ?name
WHERE ( ?x foaf:name ?name )

Limits on the number of results can also be applied via the SPARQL query protocol [11].

If both DISTINCT and LIMIT are specified, then duplicates are eliminated before the limit is applied.

Definition for SELECT

Definition: Projection

For a substitution S and a finite set of variables VS,
project(S, VS) = { (v, S[v]) | v in VS }

For a query solution Q project(Q, VS) is { project(S, V) | S in Q }

For a set QS of query solutions, project(QS, VS) is { project(Q, V) | Q in QS }

The SELECT query form is a projection of pattern solutions.

10.2 Constructing an Output Graph

The CONSTRUCT result form returns a single RDF graph specified by either a graph template or by "*". If a graph template is supplied, then the RDF graph is formed by taking each query solution and substituting the variables into the graph template and merging the triples into a single RDF graph.

CONSTRUCT with a template

If a graph template is supplied, then the RDF graph is defined to be the set of all legal RDF triples obtained by instantiating the graph template with all query solutions. If any such instantiation produces a triple containing an unbound variable, or an illegal RDF construct (such as a literal in subject or predicate position) then that triple is not included in the RDF graph, and a warning may be generated.

@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a    foaf:name   "Alice" .
_:a    foaf:mbox   <mailto:alice@example.org> .
PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
PREFIX vcard:   <http://www.w3.org/2001/vcard-rdf/3.0#>
CONSTRUCT   ( <http://example.org/person#Alice> vcard:FN ?name )
WHERE       ( ?x foaf:name ?name )
creates vcard properties corresponding to the FOAF information:
@prefix vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> .

<http://example.org/person#Alice> vcard:FN "Alice" .

Templates with bNodes

A template can create an RDF graph containing bNodes, indicated by the syntax of a prefixed name with prefix "_" and some label for the local name.  The labels are scoped to the template for each solution. If two such prefixed names share the same label in the template, then there will be one bNode created for each query solution but there will be different bNodes across triples generated by different query solutions.

@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a    foaf:givenname   "Alice" .
_:a    foaf:family_name "Hacker" .

_:b    foaf:firstname   "Bob" .
_:b    foaf:surname     "Hacker" .
PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
PREFIX vcard:   <http://www.w3.org/2001/vcard-rdf/3.0#>

CONSTRUCT   ( ?x vcard:N _:n )
            ( _:n vcard:givenName  ?gname )
            ( _:n vcard:familyName ?fname )
       { ( ?x foaf:firstname ?gname ) UNION (?x foaf:givenname   ?gname ) }
       { ( ?x foaf:surname   ?fname ) UNION (?x foaf:family_name ?fname ) }
creates vcard properties corresponding to the FOAF information:
@prefix vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> .

_:v1 vcard:N         _:x .
_:x vcard:givenName  "Alice" .
_:x vcard:familyName "Hacker" .

_:v2 vcard:N         _:z .
_:z vcard:givenName  "Bob" .
_:z vcard:familyName "Hacker" .

The use of variable ?x in the template, which in this example will be bound to bNodes, causes an equivalent graph to be constructed with a different bNode as shown by the document-scoped label.


The form CONSTRUCT * returns an RDF that is equivalent to the subgraph of the data graph that has all the triples that matched the query. It will give all the same bindings if the query is executed on the returned graph.

@prefix  foaf:  <http://xmlns.com/foaf/0.1/> .

_:a    foaf:name   "Alice" .
_:a    foaf:mbox   <mailto:alice@org> .

_:b    foaf:name   "Bob" .
_:b    foaf:mbox   <mailto:bob@org> .
CONSTRUCT * WHERE ( ?x foaf:name ?name )

Gives the result graph having just the triples with predicate foaf:name:

@prefix foaf: <http://xmlns.com/foaf/0.1/> .

_:b1 foaf:name "Bob" .
_:b2 foaf:name "Alice" .

10.3 Descriptions of Resources

The DESCRIBE form returns a single RDF graph containing RDF data associated about resources. This data is not prescribed by a SPARQL query, where the query client would need to know the structure of the RDF in the data source, but, instead, is determined by the SPARQL query processor.

The query pattern is used to create a result set. The DESCRIBE form takes each of the resources identified in a solutions, together with any resources directly named by URI, and assembles a single RDF graph by taking a "description" from the target knowledge base. The description is determined by the query processor implementation and should provide a useful description of the resource, where "useful" is left to nature of the information in the data source.

If a data source, has no information about a resource, no RDF triples are added to the result graph but the query does not fail.

10.3.1 Explicit URIs

The DESCRIBE clause itself can take URIs to identify the resources. The simplest query is just a URI in the DESCRIBE clause:

DESCRIBE <http://example.org/>

10.3.2 Identifying Resources

The resources can also be a query variable from a result set. This enables description of resources whether they are identified by URI or bNode in the dataset being queried.

PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
WHERE    (?x foaf:mbox <mailto:alice@org> )

The property foaf:mbox is defined as being an inverse function property in the FOAF vocabulary so, if treated as such, this query will return information about at most one person. If, however, the query pattern has multiple solutions, the RDF data for each is the union of all RDF graph descriptions.

PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
WHERE    (?x foaf:name "Alice" )

More than one URI or can be given:

PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
DESCRIBE ?x ?y <http://example.org/>
WHERE    (?x foaf:knows ?y)

10.3.3 Descriptions of Resources

The RDF returned is the choice of the deployment and may be dependent on the query processor implementation, data source and local configuration.  It should be the useful information the server has (within security matters outside of SPARQL) about a resource. It may include information about other resources: the RDF data for a book may also include details of the author.

A simple query such as

PREFIX ent:  <http://myorg.example/employees#> 
DESCRIBE ?x WHERE (?x ent:employeeId "1234")

might return a description of the employee and some other potentially useful details:

@prefix foaf:   <http://xmlns.com/foaf/0.1/> .
@prefix vcard:  <http://www.w3.org/2001/vcard-rdf/3.0> .
@prefix myOrg:   <http://myorg.example/employees#> .

_:a     myOrg:employeeId    "1234" ;
        foaf:mbox_sha1sum   "ABCD1234" ;
         [ vcard:Family       "Smith" ;
           vcard:Given        "John"  ] .

foaf:mbox_sha1sum  rdf:type  owl:InverseFunctionalProperty .

which includes the bNode closure for the vcard vocabulary vcard:N. For a vocabulary such as FOAF, where the resources are typically bNodes, returning sufficient information to identify a node such as the InverseFunctionalProperty foaf:mbox_sha1sum as well information which as name and other details recorded would be appropriate. In the example, the match to the WHERE clause was returned but this is not required.

10.4 Asking "yes or no" questions

Applications can use the ASK form to test whether or not a query pattern has a solution. No information is returned about the possible query solutions, just whether the server can find one or not.

@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  foaf:name       "Alice" .
_:a  foaf:homepage   <http://work.example.org/alice/> .

_:b  foaf:name       "Bob" .
_:b  foaf:mbox       <mailto:bob@work.example> .
PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
ASK  (?x foaf:name  "Alice" )

Align results to XML results format

on the same data, the following returns no match because Alice's mbox is not as described.

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
ASK  (?x foaf:name  "Alice" )
     (?x foaf:mbox  <mailto:alise@work.example> )

11 Testing Values

SPARQL expressions are constructed according to the grammar and provide access to named functions and syntactically constructed operations. The operands of these functions and operators are the subset of XML Schema DataTypes {xsd:string, xsd:integer, xsd:decimal, xsd:double, xsd:dateTime}. The SPARQL operations are listed in table 11.1 and are associated with productions in the grammar. In addition, SPARQL imports a subset of the XPath functions, listed in table 11.2, which are invoked by name within a SPARQL query. These operations are taken from the XQuery 1.0 and XPath 2.0 Functions and Operators [17].


The namespace for XPath functions that are directly available by name is http://www.w3.org/2004/07/xpath-functions. The associated namespace prefix used in this document is fn:. XPath operators are named with the prefix op:. SPARQL operators are named with the prefix sop:.

fn:string-match requires a collation to define character order and string equivilence. The XQuery 1.0 and XPath 2.0 Functions and Operators [F&O] defines the semantics of fn:string-compare and establishes a default collation. In addition, it identifies a specific collation with a distinguished name, http://www.w3.org/2004/10/xpath-functions/collation/codepoint which provides the ability to compare strings based on code point values. Every implementation of SPARQL must support the collation based on code point values.

11.1 Operand Data Types

As described above, RDF Terms are made of URIs (URI References), Literals and Blank Nodes. RDF Literals may have datatypes which may come from instance data:

@prefix a:          <http://www.w3.org/2000/10/annotation-ns#>
@prefix dc:         <http://purl.org/dc/elements/1.1/>
@prefix xsd:        <http://www.w3.org/2001/XMLSchema#>

_:a   a:annotates   <http://www.w3.org/TR/rdf-sparql-query/> .
_:a   dc:created    "2004-12-31T19:00:00-05:00" .

_:b   a:annotates   <http://www.w3.org/TR/rdf-sparql-query/> .
_:b   dc:created    "2004-12-31T19:00:01-05:00" .

Literals may be cast to typed literals:

PREFIX a:      <http://www.w3.org/2000/10/annotation-ns#>
PREFIX dc:     <http://purl.org/dc/elements/1.1/>
PREFIX xsd:    <http://www.w3.org/2001/XMLSchema#>

SELECT ?annot
WHERE ( ?annot  a:annotates  <http://www.w3.org/TR/rdf-sparql-query/> )
      ( ?annot  dc:created   ?date )
  AND xsd:dateTime(?date) < xsd:dateTime("2005-01-01T00:00Z")

SPARQL defines a subset of the XPath functions and operators when used with operands of the following XML Schema datatypes:

In addition, SPARQL introduces additional operators which operate on operands of the following RDF datatypes:

11.1.1 Type Promotion

XQuery defines a set of Numeric Type Promotions. SPARQL considers the the following four types to be numeric types:

and invokes XQuery's numeric type promotion to promote function arguments to the appropriate type. In summary: Each of the numeric types may be promoted to any type higher in the above list. The operators defined below that take numeric arguments expect all arguments to be the same type. This is accomplished by promoting the arguments to the type highest in the list. For example, xs:integer(7) + xs:float(6.5) would call op:numeric-add(xs:float(7), xs:float(6.5)). In addition, any r:Literal may be is cast to xs:string or xs:numeric when used as an argument to an operator expecting that type.

11.2 SPARQL Functions and Operators

SPARQL provides a subset of the functions and operators defined by XQuery Operator Mapping. The XPath evaluation rules are ammended by the following rules to accomodate the additional types and states introduced by RDF and SPARQL:

11.2.0 Invocation

SPARQL defines syntax for invoking functions and operators on a set of arguments. These are invoked as follows:

If any of these steps fails, the invocation generates an error. The effects of this are defined in SPARQL Functions and Operators.

Table 11.1 Operator Mapping

The SPARQL grammar identifies a set of operators (for instance, &&, *, isUri) used to construct constraints. This table associates each of these grammatical productions with an operator either defined by XQuery Operator Mapping or the additional SPARQL operators specified in section 11.2.1. The following table associates SPARQL infix operators taking specific argument types with the XPath opperation name.

SPARQL Operators
OperatorType(A)Type(B)FunctionResult type
XQuery Connectives
A || Bxs:booleanxs:boolean analogous to XQuery disjunction xs:boolean
Returns a boolean: TRUE if either A or B is true, else FALSE.
A && Bxs:booleanxs:boolean analogous to XQuery conjunction xs:boolean
Returns a boolean: TRUE if both A and B are true, else FALSE.
XPath Tests
A eq Bxs:stringxs:stringop:numeric-equal(fn:compare(A, B), 0)xs:boolean
A ne Bxs:stringxs:stringfn:not(op:numeric-equal(fn:compare(A, B), 0))xs:boolean
STRING =~ PATTERNxs:stringxs:stringfn:matches(STRING, PATTERN)xs:boolean
The XPath fn:matches can take a third argument as the collation. SPARQL does not provide a syntax for that.
STRING !~ PATTERNxs:stringxs:stringfn:not(fn:matches(STRING, PATTERN))xs:boolean
A == Bnumericnumericop:numeric-equal(A, B)xs:boolean
A == Bxs:dateTimexs:dateTimeop:dateTime-equal(A, B)xs:boolean
A != Bnumericnumericfn:not(op:numeric-equal(A, B))xs:boolean
A != Bxs:dateTimexs:dateTimefn:not(op:dateTime-equal(A, B))xs:boolean
A < Bnumericnumericop:numeric-less-than(A, B)xs:boolean
A < Bxs:dateTimexs:dateTimeop:dateTime-less-than(A, B)xs:boolean
A > Bnumericnumericop:numeric-greater-than(A, B)xs:boolean
A > Bxs:dateTimexs:dateTimeop:dateTime-greater-than(A, B)xs:boolean
A <= Bnumericnumericop:numeric-less-than(A, B) or op:numeric-equal(A, B)xs:boolean
A <= Bxs:dateTimexs:dateTimefn:not(op:dateTime-greater-than(A, B))xs:boolean
A >= Bnumericnumericop:numeric-greater-than(A, B) or op:numeric-equal(A, B)xs:boolean
A >= Bxs:dateTimexs:dateTimefn:not(op:dateTime-less-than(A, B))xs:boolean
A * Bnumericnumericop:numeric-multiply(A, B)numeric
A / Bnumericnumericop:numeric-divide(A, B)numeric; but xs:decimal if both operands are xs:integer
A + Bnumericnumericop:numeric-add(A, B)numeric
A - Bnumericnumericop:numeric-subtract(A, B)numeric
SPARQL Tests: defined in section 11.2.1
A == Br:URIr:URIsop:URI-equal(A, B)xs:boolean
Returns a boolean: TRUE if A and B are the same r:URI, else FALSE.
A != Br:URIr:URIfn:not(sop:URI-equal(A, B))xs:boolean
Returns a boolean: TRUE if A and B are not the same r:URI, else FALSE.
str(A)rdf:uri or rdf:literalN/Asop:str(A)xs:string

11.2.1 Operators introduced in SPARQL

This section defines the operators introduced by the SPARQL Query language. The names of the operators are prefixed with sop:. The examples show the behavior of the operators as invoked by the appropriate grammatical constructs. sop:URI-equal

Returns whether two arguments are the same URI. (The reader may note that this question could be asked without this operator. sop:URI-equals is useful for other purposed describe in

 ?u == ?v
@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  foaf:name       "Alice".
_:a  foaf:mbox       <mailto:alice@work.example> .

_:b  foaf:name       "Ms A.".
_:b  foaf:mbox       <mailto:alice@work.example> .

This query finds the people who have multiple foaf:name arcs:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name1 ?name2
 WHERE ( ?x foaf:name  ?name1 )
       ( ?x foaf:mbox  ?mbox1 )
       ( ?y foaf:name  ?name2 )
       ( ?y foaf:mbox  ?mbox2 )
   AND ?mbox1 == ?mbox2 && ?name1 NE ?name2

Query result:

name1 name2
"Alice" "Ms A." sop:bound

Queries with disjunction and optionals may have solutions with some unbound variables. The operator bound tests that a variable has been bound to a value. NaNs and INFs count as defined.



@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  foaf:name       "Alice".
_:a  foaf:mbox       <mailto:alice@work.example> .

_:b  foaf:name       "Bob" .

This query matches the people with a name and an mbox:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name
 WHERE ( ?x foaf:name  ?name )
         OPTIONAL ( ?x foaf:mbox ?mbox )
   AND bound(?mbox)

Query result:


Used in conjunction with optional, it can be used to test whether a graph pattern with at least one variable in it has been matched. When also used in conjunction with not, it can test to see that a triple has not been asserted. This is called Negation as Failure in logic programming.

This query matches the people with a name and no mbox:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name
 WHERE ( ?x foaf:name  ?name )
       OPTIONAL ( ?x foaf:mbox ?mbox )
   AND !bound(?mbox)

Query result:


Because Alice's mbox was known, "Alice" was not a solution to the query. sop:isURI

Returns whether a variable is bound to a URI.

@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  foaf:name       "Alice".
_:a  foaf:mbox       <mailto:alice@work.example> .

_:b  foaf:name       "Bob" .
_:b  foaf:mbox       "bob@work.example" .

This query matches the people with a name and an mbox which is a URI:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
 WHERE ( ?x foaf:name  ?name )
       ( ?x  foaf:mbox  ?mbox )
   AND isUri(?mbox)

Query result:

name mbox
"Alice" <mailto:alice@work.example> sop:isBlank

Returns whether a variable is bound to a bNode (blank node).

@prefix a:          <http://www.w3.org/2000/10/annotation-ns#>
@prefix dc:         <http://purl.org/dc/elements/1.1/>

_:a   a:annotates   <http://www.w3.org/TR/rdf-sparql-query/> .
_:a   dc:creator    "Alice B. Toeclips" .

_:b   a:annotates   <http://www.w3.org/TR/rdf-sparql-query/> .
_:b   dc:creator    _:c .
_:c   foaf:given    "Bob".
_:c   foaf:family   "Smith".

This query matches the people with a name and an mbox which is a URI:

PREFIX a:      <http://www.w3.org/2000/10/annotation-ns#>
PREFIX dc:     <http://purl.org/dc/elements/1.1/>
PREFIX xsd:    <http://www.w3.org/2001/XMLSchema#>

SELECT ?annot ?given ?family
 WHERE ( ?annot  a:annotates  <http://www.w3.org/TR/rdf-sparql-query/> )
       ( ?annot  dc:creator   ?c )
         OPTIONAL { ( ?c  foaf:given   ?given )
                    ( ?c  foaf:family  ?family ) }
   AND isBlank(?c)

Query result:

given family
"Bob" "Smith"

In this example, there were two objects of foaf:knows predicates, but only one (_:c) was a bNode. sop:isLiteral

Returns whether the argument is a literal.

@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  foaf:name       "Alice".
_:a  foaf:mbox       <mailto:alice@work.example> .

_:b  foaf:name       "Bob" .
_:b  foaf:mbox       "bob@work.example" .

This query is similar to the one in except that is matches the people with a name and an mbox which is a Literal. This would be used to look for erroneous data (foaf:mbox should only have a URI as its object).

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
 WHERE ( ?x foaf:name  ?name )
       ( ?x  foaf:mbox  ?mbox )
   AND isLiteral(?mbox)

Query result:

name mbox
"Bob" "bob@work.example" sop:str

Returns an xs:string representation of an r:URI. This useful for examining parts of a URI, for instance, the hostname.

@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  foaf:name       "Alice".
_:a  foaf:mbox       <mailto:alice@work.example> .

_:b  foaf:name       "Bob" .
_:b  foaf:mbox       <mailto:bob@home.example> .

This query selects the set of people who use their work.example address in their foaf profile:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
 WHERE { ( ?x foaf:name  ?name )
         ( ?x  foaf:mbox  ?mbox ) }
   AND str(?mbox) =~ m/@work.example$/

Query result:

name mbox
"Alice" <alice@work.example> sop:lang

Returns a valid RFC 3066 language string representing the XML schema language datatype for a variable.

@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .

_:a  foaf:name       "Robert"@EN.
_:a  foaf:name       "Roberto"@ES.
_:a  foaf:mbox       <mailto:bob@work.example> .

This query finds the Spanish foaf:name and foaf:mbox:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name1
 WHERE ( ?x foaf:name  ?name )
       ( ?x foaf:mbox  ?mbox )
       AND lang(?mbox) EQ "ES"

Query result:

name mbox
"Roberto" <mailto:bob@work.example> sop:datatype

Returns the datatype of its argument if that argument is a typed literal. Otherwise it fails.

@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:       <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd:        <http://www.w3.org/2001/XMLSchema#> .

_:a  foaf:name       "alice".
_:a  foaf:shoeSize   "9.5"^^xsd:float .

_:b  foaf:name       "bob".
_:b  foaf:shoeSize   "42"^^<http://...integer> .

This query finds everyone's foaf:name and integer foaf:shoeSize:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?size
 WHERE ( ?x foaf:name  ?name )
       ( ?x foaf:shoeSize  ?size )
   AND datatype(?size) == <http://...integer>

Query result:

name shoeSize
"Bob" 42

Table 11.2 SPARQL Functions

SPARQL imports casting functions from the XPath. The XQuery Functions & Operators Primative Type Mapping table [17] specifies a which primative types are castable to which other primative types. The table is reproduced below, omitting casting operations that are not in the SPARQL language, and adding the additional datatypes imposed by the RDF data model.

bool = xs:boolean
dbl = xs:double
flt = xs:float
dec = xs:decimal
int = xs:integer
dT = xs:dateTime
str = xs:string
URI = r:URIRef — introduced by the RDF data model
ltrl = r:Literal — introduced by the RDF data model

S\T str flt dbl dec int dT bool URI ltrl
str Y M M M M M M M M
flt Y Y Y M M N Y N N
dbl Y Y Y M M N Y N N
dec Y Y Y Y Y N Y N N
int Y Y Y Y Y N Y N N
dT Y N N N N Y N N N
bool Y Y Y Y Y N Y N N
ltrl Y M M M M M M M Y

11.3 Extensible Value Testing

Implementations may provide custom extended value testing operations, for example, for specialised datatypes. These are provided by functions in the query that return true or false for their arguments.

&qname(?var or constant, ?var or constant , ...)


PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
 WHERE { ( ?x foaf:name  ?name )
         ( ?x  foaf:mbox  ?mbox ) }
   AND my:even(str(?mbox))

A function can test some condition of bound and unbound variables or constants. The function is called for each possible query result (or the equivalent effect if optimized in some way). A function is named by URIRef in a QName form, and returns a boolean value. "true" means accept; "false" means reject this solution.

If a query processor encounters a function that it does not provide, the query is not executed and an error is returned.

Functions should have no side-effects.  A SPARQL query processor may remove calls to functions if it can optimize them away. A SPARQL query processor may call to a function more than once for the same solution.

A. SPARQL Grammar

Section status: drafted – terminal syntax not checked against that of the XML 1.1 spec

A sparql query is a sequence of characters in the language defined by the following grammar, starting with the Query production. The EBNF format is the same as that used in the XML 1.1 specification. Please see the "Notation" section of that specification for specific information about the notation.

References to lexical tokens are enclosed in <>. Whitespace is skipped.

Comments in SPARQL queries take the form of '#', outside a URI or string, and continue to the end of line or end of file if there is no end of line after the comment marker.

Notes: The term "literal" refers to a constant value, and not only an RDF Literal.

[1]   Query   ::=   Prolog
( SelectClause |
  ConstructClause |
  DescribeClause |
( GraphClause )*
( NamedGraphClause )*
( WhereClause )?
( LimitClause )?
[2]   Prolog   ::=   ( BaseDecl )? ( PrefixDecl )*
[3]   SelectClause   ::=     'select' ( 'distinct' )? ( VarAsNode )+
| 'select' ( 'distinct' )? '*'
[4]   DescribeClause   ::=     'describe' ( VarOrURI )+
| 'describe' '*'
[5]   ConstructClause   ::=     'construct' ConstructPattern
| 'construct' '*'
[6]   AskClause   ::=   'ask'
[7]   GraphClause   ::=   'WITH' ( SourceSelector )+
[8]   NamedGraphClause   ::=   'from' ( SourceSelector )+
[9]   SourceSelector   ::=   URI
[10]   WhereClause   ::=   'where' GraphPattern
[11]   LimitClause   ::=   'limit' Integer
[12]   GraphPattern   ::=   PatternGroup
[13]   PatternGroup   ::=   GraphOrPattern
[14]   GraphOrPattern   ::=   GraphAndPattern ( 'union' GraphAndPattern )*
[15]   GraphAndPattern   ::=   ( PatternElement )+
[16]   PatternElement   ::=     TriplePattern
| GroupGraphPattern
| NamedGraphPattern
| OptionalGraphPattern
| 'and' ConstraintPattern
[17]   PatternElementAsGroup   ::=   PatternElement
[18]   GroupGraphPattern   ::=   '{' PatternGroup '}'
[19]   NamedGraphPattern   ::=     'graph' '*' PatternElementAsGroup
| 'graph' VarOrURI PatternElementAsGroup
[20]   OptionalGraphPattern   ::=   'optional' PatternElementAsGroup
[21]   ConstraintPattern   ::=   Expression
[22]   TriplePattern   ::=   '(' VarOrURI VarOrURI VarOrLiteral ')'
[23]   ConstructPattern   ::=   ( ConstructElement )+
[24]   ConstructElement   ::=   TripleTemplate
[25]   TripleTemplate   ::=   '(' ( VarOrURI
| BNode ) VarOrURI ( VarOrLiteral
| BNode ) ')'
[26]   VarOrURI   ::=     VarAsNode
[27]   VarOrLiteral   ::=     VarAsNode
| Literal
[28]   VarAsNode   ::=   <VAR>
[29]   VarAsExpr   ::=   <VAR>
[30]   BaseDecl   ::=   'base' QuotedURI
[31]   PrefixDecl   ::=     'prefix' <QNAME_NS> QuotedURI
| 'prefix' ':' QuotedURI
[32]   Expression   ::=   ConditionalOrExpression
[33]   ConditionalOrExpression   ::=   ConditionalXorExpression
( '||' ConditionalXorExpression )*
[34]   ConditionalXorExpression   ::=   ConditionalAndExpression
[35]   ConditionalAndExpression   ::=   ValueLogical ( '&&' ValueLogical )*
[36]   ValueLogical   ::=   StringEqualityExpression
[37]   StringEqualityExpression   ::=   NumericalLogical
( 'eq' NumericalLogical
| 'ne' NumericalLogical
| <STR_MATCH> PatternLiteral
| '!~' PatternLiteral )*
[38]   NumericalLogical   ::=   EqualityExpression
[39]   EqualityExpression   ::=   RelationalExpression
( '==' RelationalExpression
| '!=' RelationalExpression )?
[40]   RelationalExpression   ::=   NumericExpression
( '<' NumericExpression
| '>' NumericExpression
| '<=' NumericExpression
| '>=' NumericExpression )?
[41]   NumericExpression   ::=   AdditiveExpression
[42]   AdditiveExpression   ::=   MultiplicativeExpression
( '+' MultiplicativeExpression
| '-' MultiplicativeExpression )*
[43]   MultiplicativeExpression   ::=   UnaryExpression
( '*' UnaryExpression
| '/' UnaryExpression
| '%' UnaryExpression )*
[44]   UnaryExpression   ::=   ( '~'
| '!' ) BuiltinExpression
| '+' BuiltinExpression
| '-' BuiltinExpression
| BuiltinExpression
[45]   BuiltinExpression   ::=     'bound' '(' VarAsExpr ')'
| 'str' '(' VarOrLiteralAsExpr ')'
| 'lang' '(' VarOrLiteralAsExpr ')'
| 'datatype' '(' VarOrLiteralAsExpr ')'
| 'isURI' '(' VarOrLiteralAsExpr ')'
| 'isBlank' '(' VarOrLiteralAsExpr ')'
| 'isLiteral' '(' VarOrLiteralAsExpr ')'
| URI '(' Expression ')'
| PrimaryExpression
[46]   PrimaryExpression   ::=     VarAsExpr
| Literal
| FunctionCall
| '(' Expression ')'
[47]   FunctionCall   ::=   '&' URI '(' ArgList ')'
[48]   ArgList   ::=   ( VarOrLiteralAsExpr ( ',' VarOrLiteralAsExpr )* )?
[49]   VarOrLiteralAsExpr   ::=     Literal
| VarAsExpr
[50]   Literal   ::=   URI
| NumericLiteral
| TextLiteral
[51]   NumericLiteral   ::=   Integer
| FloatingPoint
[52]   TextLiteral   ::=   ( <STRING_LITERAL1>
( <LANGTAG> )?
( '^^' URI )?
[53]   PatternLiteral   ::=   Perl 5 regular expression
[54]   URI   ::=   QuotedURI
| QName
[55]   QName   ::=   <QNAME> | <QNAME_NS>
[56]   BNode   ::=   <BNODE>
[57]   QuotedURI   ::=   <Q_URI>
[58]   Integer   ::=   <INTEGER_10> | <INTEGER_16>
[59]   FloatingPoint   ::=   <FLOATING_POINT>
[60]   <PATTERN>   ::=   Perl 5 regular expression
[61]   <Q_URI>   ::=   "<"
(<NCCHAR1> |"#" |"_") (~[">"," "])*
[62]   <QNAME_NS>   ::=   (<NCNAME1>)? ":"
[63]   <QNAME>   ::=   (<NCNAME1>)? ":" (<NCNAME1>
[64]   <BNODE>   ::=     "_:"
| <NCNAME2>)
[65]   <VAR>   ::=   ("?" |"$") (<NCNAME2> |<NCNAME1>)
[66]   <LANGTAG>   ::=   '@' (<A2Z>)+("-" (<A2ZN>)+)?
[67]   <A2Z>   ::=   ["a"-"z","A"-"Z"]
[68]   <A2ZN>   ::=   ["a"-"z","A"-"Z","0"-"9"]
[69]   <INTEGER_10>   ::=   <DIGITS>
[70]   <INTEGER_16>   ::=   "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+
[71]   <FLOATING_POINT>   ::=   (["0"-"9"])+ "." (["0"-"9"])* (<EXPONENT>)?
| "." (["0"-"9"])+ (<EXPONENT>)?
| (["0"-"9"])+ <EXPONENT>
[72]   <EXPONENT>   ::=   ["e","E"] (["+","-"])? (["0"-"9"])+
[73]   <STRING_LITERAL1>   ::=   "'"
( (~["'","\\","\n","\r"]) | ("\\" ~["\n","\r"]) )*
[74]   <STRING_LITERAL2>   ::=   "\""
( (~["\"","\\","\n","\r"]) | ("\\" ~["\n","\r"]) )*
[75]   <DIGITS>   ::=   (["0"-"9"])+
[76]   <STR_MATCH>   ::=    "=~" |"~~"
[77]   <NCCHAR1>   ::=     ["A"-"Z"]
| ["a"-"z"]
| ["\u00C0"-"\u00D6"]
| ["\u00D8"-"\u00F6"]
| ["\u00F8"-"\u02FF"]
| ["\u0370"-"\u037D"]
| ["\u037F"-"\u1FFF"]
| ["\u200C"-"\u200D"]
| ["\u2070"-"\u218F"]
| ["\u2C00"-"\u2FEF"]
| ["\u3001"-"\uD7FF"]
| ["\uF900"-"\uFFFF"]
[78]   <NCCHAR_FULL>   ::=     <NCCHAR1>
| "_"
| "."
| "-"
| ["0"-"9"]
| "\u00B7"
[79]   <NCNAME1>   ::=   <NCCHAR1> (<NCCHAR_FULL>)*
[80]   <NCNAME2>   ::=   "_" (<NCCHAR_FULL>)*

B. References


[1] "Three Implementations of SquishQL, a Simple RDF Query Language", Libby Miller, Andy Seaborne, Alberto Reggiori; ISWC2002

[2] "RDF Query and Rules: A Framework and Survey", Eric Prud'hommeaux

[3] "RDF Query and Rule languages Use Cases and Example", Alberto Reggiori, Andy Seaborne

[4] RDQL Tutorial for Jena (in the Jena tutorial).

[5] RDQL BNF from Jena

[6] Enabling Inference, R.V. Guha, Ora Lassila, Eric Miller, Dan Brickley

[7] N-Triples

[8] RDF http://www.w3.org/RDF/

[9] "Representing vCard Objects in RDF/XML", Renato Iannella, W3C Note.

[10] "RDF Data Access Working Group"

[11] "RDF Data Access Use Cases and Requirements ? W3C Working Draft 2 June 2004", Kendall Grant Clark.

[12] "Resource Description Framework (RDF): Concepts and Abstract Syntax", Graham Klyne, Jeremy J. Carroll, W3C Recommendation.

[13] RFC 3986, "Uniform Resource Identifier (URI): Generic Syntax", T. Berners-Lee, R. Fielding, L. Masinter

[14] "Namespaces in XML 1.1", Tim Bray et al., W3C Recommendation.

[15] "Turtle - Terse RDF Triple Language, Dave Beckett.

[16] "SPARQL Variable Binding Results XML Format", Dave Beckett.

[17] "XQuery 1.0 and XPath 2.0 Functions and Operators", Ashok Malhotra et al., W3C Working Draft.

Valid XHTML 1.0!

C. Change Log

CVS Change Log:

Revision 1.224  2005/02/17 19:22:44  eric
link text for change log

Revision 1.223  2005/02/17 19:20:27  eric
filled out change log to include everything from last publication

Revision 1.222  2005/02/17 19:08:33  eric
third pass at pubrules checker

Revision 1.221  2005/02/17 18:34:02  eric
second pass at pubrules checker

Revision 1.220  2005/02/17 18:11:59  eric
first pass at pubrules checker

Revision 1.219  2005/02/17 17:48:47  eric

Revision 1.218  2005/02/17 17:38:30  eric
+ added publication template
+ updated status of this document
+ removed vestigial stati
+ links to turtle, protocol, XML results format
+ links to xs data types

Revision 1.217  2005/02/17 13:21:10  eric
+ invocation and promotion sections sufficient for publication

Revision 1.216  2005/02/17 11:26:44  aseaborne
+ Fixup in sections 1 and 2.

Revision 1.215  2005/02/17 11:14:02  eric
+ work on invocation and promotion

Revision 1.214  2005/02/17 05:26:34  eric
advice from the chari on wording objections

Revision 1.213  2005/02/16 19:16:40  eric
changes from DanC's process issues.

Revision 1.212  2005/02/16 15:31:55  eric
tiny bit of space pre formatting in SPARQL queries

Revision 1.211  2005/02/16 15:28:32  eric
new examples for 11.1 and

Revision 1.210  2005/02/16 11:56:41  aseaborne
+ Editorial corrections from DaveB : /2005JanMar/0145.html

Revision 1.209  2005/02/15 16:57:24  aseaborne
+ Optional syntax is OPTIONAL
  Removed use of [] as an alternative
  Chnaged grammar
+ Typos

Revision 1.208  2005/02/15 16:27:51  eric
bugfixes with AndyS and SteveH post 15-Feb telecon

Revision 1.207  2005/02/15 15:35:13  eric
fixed examples and clarified operators example

Revision 1.206  2005/02/15 15:15:08  eric
more of steve's comments

Revision 1.205  2005/02/15 11:03:48  aseaborne
Corrections from Alberto

Revision 1.204  2005/02/10 11:16:43  aseaborne
+ Changed LOAD to WITH

Revision 1.203  2005/02/10 09:53:41  eric
incorporated some of SteveH's comments

Revision 1.202  2005/02/09 12:40:13  aseaborne
+ Restored correct text for 10.1
+ Inserted XML result set example output

Revision 1.201  2005/02/09 11:26:21  aseaborne
+ Updated grammar
+ Fixed some of the errors that returned after text restore in 10.2

Revision 1.200  2005/02/08 14:36:49  eric
fixed TOC

Revision 1.199  2005/02/08 14:35:20  eric
reduce casting table

Revision 1.198  2005/02/08 12:36:47  aseaborne
*** empty log message ***

Revision 1.197  2005/02/07 11:32:49  aseaborne
+ Better (?) definition for GRAPH (sec 8.5)

Revision 1.196  2005/02/07 10:11:34  aseaborne
+ Turned all "URI references" into "URIs" now RFC 3986 has been published
+ Added preliminary definition for GRAPH (sec 8.5)

Revision 1.195  2005/02/04 13:12:39  eric
+clarified SPARQL datatypes

Revision 1.194  2005/02/04 10:21:59  eric
+ fixed up operand data types
+ clarified operator mapping
- removed vestigial text

Revision 1.193  2005/02/03 20:21:40  eric
+ flushed out SPARQL ops

Revision 1.192  2005/02/03 13:22:13  eric
+ added BOUND

Revision 1.191  2005/02/03 11:32:44  eric
+ aggregate data mode for F&O

Revision 1.190  2005/02/03 08:57:06  eric
+ progress on mapping tables

Revision 1.189  2005/02/02 07:18:21  eric
normalized CONSTRUCT heading

Revision 1.188  2005/02/01 17:56:01  aseaborne
+ More s/unnamed/background/g

Revision 1.187  2005/02/01 10:56:24  aseaborne
+ More grammar appearance tweaks.  More on exact layout to do.

Revision 1.186  2005/02/01 10:28:09  aseaborne
+ Grammar tweaks.  More on exact layout to do.

Revision 1.185  2005/02/01 09:27:05  eric

Revision 1.184  2005/02/01 09:23:32  eric
+ more context for F&O

Revision 1.183  2005/01/31 17:23:20  aseaborne
+ CONSTRUCT/template text as per PatH's suggestion
+ Removed sec 3.4 (constaints and predicates)
+ Removed sec 3.3 (implementation requirements)
  If there is anything to note, should be in sec "Testing Values"
  where XSD datatypes covered
+ Removed red text where it no longer made sense
  (either there is proposed text or the point is
   no longer relevant)

Revision 1.182  2005/01/31 15:33:08  aseaborne
+ New version of the grammar
  New (to be checked) process to produce it mechanically
  for validated javacc file

Revision 1.181  2005/01/28 19:42:55  aseaborne
+ s/unnamed/background/ in RDF Dataset defn

Revision 1.180  2005/01/28 18:58:19  aseaborne
+ Reworded RDF dataset description text

Revision 1.179  2005/01/28 08:48:20  eric
+ a couple examples

Revision 1.178  2005/01/27 14:09:29  aseaborne
+ Put RDF dataset abstract description into own section
+ Changes to LOAD/FROM/GRAPH from F2F/Finland - in progress

Revision 1.177  2005/01/27 09:42:46  eric
+ re-added cvs log

revision 1.176
date: 2005/01/27 09:31:31;  author: eric;  state: Exp;  lines: +11 -8
= validated

revision 1.175
date: 2005/01/27 09:14:24;  author: eric;  state: Exp;  lines: +61 -6
+ operators table for discussion

revision 1.174
date: 2005/01/25 18:01:40;  author: aseaborne;  state: Exp;  lines: +6 -7

revision 1.173
date: 2005/01/25 16:05:59;  author: aseaborne;  state: Exp;  lines: +14 -10

revision 1.172
date: 2005/01/25 09:37:39;  author: aseaborne;  state: Exp;  lines: +61 -435
+ Removed UNSAID section
+ Truncated CVS log

revision 1.171
date: 2005/01/17 13:40:05;  author: aseaborne;  state: Exp;  lines: +7 -4

revision 1.170
date: 2005/01/14 16:16:03;  author: aseaborne;  state: Exp;  lines: +14 -6
+ Reworked sec 5 (groups of patterns)

revision 1.169
date: 2005/01/11 18:21:03;  author: aseaborne;  state: Exp;  lines: +1 -1

revision 1.168
date: 2005/01/11 16:46:27;  author: aseaborne;  state: Exp;  lines: +21 -13
+ Reworked sec 5 (groups of patterns)

revision 1.167
date: 2005/01/11 16:10:39;  author: aseaborne;  state: Exp;  lines: +17 -14

revision 1.166
date: 2005/01/10 17:59:34;  author: aseaborne;  state: Exp;  lines: +56 -29
+ Some restructuring of the DESCRIBE text

revision 1.165
date: 2005/01/10 16:16:54;  author: aseaborne;  state: Exp;  lines: +39 -45
+ Worked on text on sec 5 (optionals)

revision 1.164
date: 2005/01/10 11:34:40;  author: aseaborne;  state: Exp;  lines: +102 -12
+ Added an example (section 9.4) with both named and unnamed graphs
  in the dataset.  The unnamed graph is used for provenance information.

revision 1.163
date: 2005/01/07 17:07:08;  author: aseaborne;  state: Exp;  lines: +12 -3
*** empty log message ***

revision 1.162
date: 2005/01/06 18:19:53;  author: aseaborne;  state: Exp;  lines: +93 -170
+ Minor changes to CONSTRUCT text
+ Reverse CONSTRUCT * and CONSTRUCT template sections
+ Tidying up sec 9 (in progress)

revision 1.161
date: 2005/01/05 17:13:28;  author: aseaborne;  state: Exp;  lines: +194 -19
+ Major revision to section8 (FROM and GRAPH)

revision 1.160
date: 2004/12/17 18:16:17;  author: aseaborne;  state: Exp;  lines: +26 -28
+ Started making section 9 "untrusted graphs"
  (Not started on sec 8 yet)

revision 1.159
date: 2004/12/17 10:23:57;  author: aseaborne;  state: Exp;  lines: +137 -96
+ Swapped Grouping to section to before optional
  Grouing is now section 4, Optionals is now section 5
+ Put all discussion of optionals and the rules for
  variables into optional section

revision 1.158
date: 2004/12/14 16:14:49;  author: aseaborne;  state: Exp;  lines: +45 -18
Added sections 3.3 (Implementation of constraints)
and 3.4 (Constraints and Predicates)

Change example in section 5 based on

revision 1.157
date: 2004/12/14 09:57:22;  author: aseaborne;  state: Exp;  lines: +43 -61
Added sections 3.3 (Implementation of constrinats)
and 3.4 (Constraints and Predicates)

revision 1.156
date: 2004/12/13 17:41:16;  author: eric;  state: Exp;  lines: +14 -11
updated formal defn for UNSAID to TLR's text

revision 1.155
date: 2004/12/12 22:34:18;  author: eric;  state: Exp;  lines: +70 -65
added class to production tbody

revision 1.154
date: 2004/12/12 22:10:42;  author: eric;  state: Exp;  lines: +10 -7

revision 1.153
date: 2004/12/10 17:21:57;  author: aseaborne;  state: Exp;  lines: +9 -4
Refine notes on value constraints

revision 1.152
date: 2004/12/10 16:55:05;  author: aseaborne;  state: Exp;  lines: +67 -39
More changes baed on Pat's input (sec 2.4 & 2.5, 3.1)

revision 1.151
date: 2004/12/10 16:27:03;  author: eric;  state: Exp;  lines: +10 -11
fixed some types in 2nd UNSAID example

revision 1.150
date: 2004/12/10 15:41:05;  author: aseaborne;  state: Exp;  lines: +145 -301
Revision based on comments and rewritten definitions by PatH.
(sec 1 and 2 to 2.4)

revision 1.149
date: 2004/12/10 15:17:56;  author: eric;  state: Exp;  lines: +20 -13
clarified when UNSAID can reference OPTIONAL or UNION vars

revision 1.148
date: 2004/12/09 17:11:57;  author: eric;  state: Exp;  lines: +146 -6
added UNSAID

revision 1.147
date: 2004/12/07 19:16:05;  author: aseaborne;  state: Exp;  lines: +8 -5
Fixed link in TOC to sec 11.1, 11.3

revision 1.146
date: 2004/12/06 10:04:50;  author: aseaborne;  state: Exp;  lines: +12 -10
Matching is by subgraph

revision 1.145
date: 2004/12/03 15:33:15;  author: aseaborne;  state: Exp;  lines: +32 -17
Changes suggested by Kevin: section 10
+ (sec 2.3) Added text introducing Query Pattern
+ (sec 2.3) Added definition for Query Pattern
+ Changed [] to _: style bnodes

revision 1.144
date: 2004/12/02 17:11:19;  author: aseaborne;  state: Exp;  lines: +145 -87
Changes suggested by Kevin: section 3,4,5,6
+ Use "solutions" languages, not "matches" language in text
+ wordsmithing
+ New section 4.2 Constraints in optionals.
+ Changed query involving nested optionals
+ Changed var names in second example OR query of DC10 and DC11.

revision 1.143
date: 2004/12/02 12:23:59;  author: aseaborne;  state: Exp;  lines: +14 -8
Changes from comments on coments.

revision 1.142
date: 2004/12/01 16:38:05;  author: aseaborne;  state: Exp;  lines: +38 -36
+ spellcheck

+ Changed UNION to OR.

revision 1.141
date: 2004/12/01 16:24:08;  author: aseaborne;  state: Exp;  lines: +86 -89
Changes for sections 1 and 2 based on email from KevinW

revision 1.140
date: 2004/11/28 08:28:53;  author: eric;  state: Exp;  lines: +553 -1249
updated to reflect andy's current grammar

revision 1.139
date: 2004/11/22 16:52:02;  author: aseaborne;  state: Exp;  lines: +32 -9
+ "subgraph" => simple entail in def of Graph Pattern Matching
+ Noted generalization for TriplePatterns to be uniform.
+ sec 11: added op:anyURI-equals to list of tests
+ removed "casting" from eq/ne.

revision 1.138
date: 2004/11/22 11:36:06;  author: aseaborne;  state: Exp;  lines: +50 -45
*** empty log message ***

revision 1.137
date: 2004/11/19 17:44:46;  author: aseaborne;  state: Exp;  lines: +228 -117
Section 8 drafted, based on DaveB email

revision 1.136
date: 2004/11/19 09:29:26;  author: eric;  state: Exp;  lines: +40 -13
integrated some comments from http://lists.w3.org/Archives/Public/public-rdf-dawg/2004OctDec/0241.html

revision 1.135
date: 2004/11/18 18:33:29;  author: eric;  state: Exp;  lines: +26 -15
use new introductory example

revision 1.134
date: 2004/11/17 16:17:15;  author: aseaborne;  state: Exp;  lines: +25 -26
Tidy up of some markup

revision 1.133
date: 2004/11/17 16:09:26;  author: aseaborne;  state: Exp;  lines: +214 -92
*** empty log message ***

revision 1.132
date: 2004/11/15 15:44:16;  author: aseaborne;  state: Exp;  lines: +56 -51
+ Move 4.3 (Nested optionals) to 5.1
+ Section 8 : added first part of text from DaveB
  (awaiting clarification before doing rest).

revision 1.131
date: 2004/11/12 15:24:29;  author: aseaborne;  state: Exp;  lines: +11 -4
Replace text mistakenly deleted in first Graph Pattern defintion

revision 1.130
date: 2004/11/12 14:50:43;  author: aseaborne;  state: Exp;  lines: +133 -62
Hopefully, I have:
+ Removed all commas from query examples.
+ changed "Set of bindings" => "Substitution"

revision 1.129
date: 2004/11/10 18:09:55;  author: aseaborne;  state: Exp;  lines: +38 -15
+ Added a little text to 2.5 that discusses bNodes.
+ Added definition of projection to SELECT result form.

revision 1.128
date: 2004/11/08 15:27:14;  author: aseaborne;  state: Exp;  lines: +96 -25
+ Section 3 renamed and split into subsections on
  literal matching and testing values.

revision 1.127
date: 2004/11/05 15:32:42;  author: aseaborne;  state: Exp;  lines: +180 -14
+ Added text about UNION in the section on alternatives.
  (not complete but outlines a design)

revision 1.126
date: 2004/11/04 15:20:29;  author: aseaborne;  state: Exp;  lines: +94 -138
+ ASK examples done: one that asnwers "yes" and one that answers "no"
+ triple pattern grouping is now {braces} (except for [] optionals)
+ Results from SELECT are sets (but implementations may include duplicates
  unless DISTINCT).
+ Text for error conditions in CONSTRUCT

revision 1.125
date: 2004/10/25 13:02:12;  author: aseaborne;  state: Exp;  lines: +7 -4
foaf:box => foaf:mbox in 2.4

revision 1.124
date: 2004/10/25 12:44:14;  author: aseaborne;  state: Exp;  lines: +12 -8
Types and trying to get ,spell to not give seemingly false negatives.

revision 1.123
date: 2004/10/25 12:40:38;  author: aseaborne;  state: Exp;  lines: +12 -6
Editoprial changes based on comments in:

revision 1.122
date: 2004/10/25 11:18:59;  author: aseaborne;  state: Exp;  lines: +18 -8

revision 1.121
date: 2004/10/25 11:14:53;  author: aseaborne;  state: Exp;  lines: +40 -380
Chnages based on comments in:

+ Trimmed log back to working draft publication point.
+ Added 4.3 which talks about nested optional blocks.
+ Removed discussion in sec 12 on contrainst and grpah pattern matching.
+ section 2.5 to discuss bNodes in queries (can't have them) and
  in results (doc-scoped ids only).
+ section 3 says that errors in constraints lead to solution rejection
  Includes bNodes for numeric comparisions.

revision 1.120
date: 2004/10/19 20:32:32;  author: connolly;  state: Exp;  lines: +40 -69
replace ficticious status with true status
add tbody markup (required by nxml-mode's rng schema, at least)

revision 1.119
date: 2004/10/15 16:00:42;  author: aseaborne;  state: Exp;  lines: +21 -4
Added notes on various ways to access RDF literals

revision 1.118
date: 2004/10/15 14:31:23;  author: eric;  state: Exp;  lines: +15 -10
- added latest published version link
- XML validated