W3C

SPARQL Query Language for RDF

W3C Working Draft 23 November 2005

This version:
http://www.w3.org/TR/2005/WD-rdf-sparql-query-20051123/
Previous version:
http://www.w3.org/TR/2005/WD-rdf-sparql-query-20050721/
Latest version:
http://www.w3.org/TR/rdf-sparql-query/
Editors:
Eric Prud'hommeaux, W3C <eric@w3.org>
Andy Seaborne, Hewlett-Packard Laboratories, Bristol <andy.seaborne@hp.com>

Abstract

RDF is a flexible and 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 artifacts, 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 the SPARQL Protocol And RDF Query Language for easy access to RDF stores. It is designed to meet the requirements and design objectives described in RDF Data Access Use Cases and Requirements [UCNR]

Status of This document

This is the fifth 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.

The change log enumerates changes since the 21 July 2005 Working Draft. Also, since that draft, we have been tracking threads in the public-rdf-dawg-comments archive more closely. A status report is updated every week or so. It shows which comments are open (unaddressed), pending (addressed but not confirmed) and closed (addressed and confirmed).

For at least part of each of the following comments, this draft has a proposal that the WG is considering:

  1. SPARQL: W3C QA Guidelines conformance
  2. SPARQL: language tag issues
  3. SPARQL: Error handling
  4. SPARQL: isURI poorly named
  5. SPARQL: format based on Unicode?
  6. Example Errors
  7. Comments on SPARQL from the XML Query and the XSL WGs
  8. Namespaces
  9. Comments on last-call SPARQL draft 20050721, sections 3 onwards

5 comments are connected to an open WG issue, rdfSemantics, that is not addressed in this draft:

  1. 2005-09-01T17:12:32Z from Art.Barstow
  2. 2005-09-08T01:26:59Z from pfps
  3. 2005-09-18T15:02:48Z from pfps, 2005-09-23T14:34:50Z from pfps
  4. 2005-09-09T20:39:31Z from horrocks via connolly
  5. 2005-10-28T11:45:37Z from herman.ter.horst
  6. 2005-09-01T11:27:51Z from GK

Comments since about 1 Nov have not yet been addressed. They include:

  1. SPARQL Comments (Personal)
  2. sparql describe - options?!
  3. CONSTRUCT: allow *?

For the definitions, we have an XSLT transformation, defns.xsl, that extracts them from this document. A live version of the output is available via the W3C XSLT service.

See also: SPARQL Test Cases, in progress.

Editorial notes in "issue" style highlight issues or outstanding dissent. "todo" style indicates an area where the editors will 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

Appendices


1 Introduction

An RDF graph is a set of triples; each triple consists of a subject, a predicate and an object. This is defined in RDF Concepts and Abstract Syntax[CONCEPTS]. 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 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. The companion SPARQL Protocol for RDF document [SPROT] describes the remote access protocol.

1.1 Document Conventions

In this document, examples assume the following namespace prefix bindings unless otherwise stated:

PrefixIRI
rdf http://www.w3.org/1999/02/22-rdf-syntax-ns#
rdfs http://www.w3.org/2000/01/rdf-schema#
xsd http://www.w3.org/2001/XMLSchema#

2 Making Simple Queries

The SPARQL query language is based on matching graph patterns. The simplest graph pattern is the triple pattern, which is like an RDF triple but with the possibility of a variable in any of the subject, predicate or object positions. Combining these gives a basic graph pattern, where an exact match to a graph is needed to fulfill a pattern.

Later sections of this document describe how other graph patterns can be built using the graph operators OPTIONAL and UNION; how graph patterns can be grouped together; how queries can extract information from more than one graph, and how it is also possible to restrict the values allowed in matching a pattern.

In this section, we cover simple triple patterns, basic graph patterns as well as the SPARQL syntax for basic pattern 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 the given RDF graph. The query consists of two parts, the SELECT clause and the WHERE clause. The SELECT clause identifies the variables to appear in the query results, and the WHERE clause has one triple pattern.

Data:

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

Query:

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

Query Result:

title
"SPARQL Tutorial"

2.1.1 Syntax of IRI Terms

The terms delimited by "<>" are IRI references [RFC3987]. They stand for IRIs, either directly, or relative to a base IRI.  IRIs are a generalization of URIs [RFC3986] and are fully compatible with URIs and URLs.

SPARQL provides a two abbreviation mechanisms for IRIs, namespace prefixes and relative IRIs.

The PREFIX keyword binds a prefix to a namespace IRI [NAMESPACE]. A prefix binding applies to any QNames in the query with that prefix; a prefix may be defined only once. A QName is mapped to an IRI by appending the local name to the namespace IRI corresponding to the prefix.

Relative IRIs are combined with base IRIs as per Uniform Resource Identifier (URI): Generic Syntax [RFC3986] using only the basic algorithm in Section 5.2 . Neither Syntax-Based Normalization nor Scheme-Based Normalization (described in sections 6.2.2 and 6.2.3 of RFC3986) is performed. Characters additionally allowed in IRI references are treated in the same way that unreserved characters are treated in URI references, per section 6.5 of Internationalized Resource Identifiers (IRIs) [RFC3987].

The BASE keyword defines the Base IRI used to resolve relative IRIs per RFC3986 section 5.1.1, "Base URI Embedded in Content". Section 5.1.2, "Base URI from the Encapsulating Entity" defines how the Base IRI may come from a an encapsulating document, such as a SOAP envelope with an xml:base directive, or a mime multipart document with a Content-Location header. The "Retrieval URI" identified in 5.1.3, Base "URI from the Retrieval URI", is the URL from which a particular SPARQL query was retrieved.

2.1.2 Syntax of Literal Terms

The query terms can be literals which are a string (enclosed in quotes, either double quotes "" or single quotes '' ), with either an optional language tag (introduced by @) or an optional datatype IRI or qname (introduced by ^^). As a convenience, integers can be written directly and are interpreted as typed literals of datatype xsd:integer; decimal numbers are interpreted as xsd:decimal and a numer with an exponent is interpreted as an xsd:double. Values of type xsd:boolean can also be written as true or false.

2.1.3 Syntax of Variables

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

2.1.4 Syntax of Triple Patterns

Triple Patterns are written as a list of subject, predicate, object; there are abbreviated ways of writing some common triple pattern constructs. Triple Patterns are grouped together with {}(braces).

2.1.5 Examples of Query Syntax

The following examples express the same query:

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 }
BASE    <http://example.org/book/>
PREFIX  dc: <http://purl.org/dc/elements/1.1/>
SELECT  ?title
WHERE   { <book1>  dc:title  ?title }

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

BASE    <http://example.org/book/>
PREFIX  dcore:  <http://purl.org/dc/elements/1.1/>
SELECT  ?title
WHERE   { <book1> dcore:title ?title }

2.1.6 Data descriptions used in this document

The data format used in this document is Turtle [TURTLE], used to show each triple explicitly. Turtle allows URIs to be abbreviated with prefixes:

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

2.1.7 Result Descriptions used in this document

The term "binding" is used as a descriptive term to refer to a pair of (variable, RDF term). In this document, we illustrate results in tabular form. 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.

Results can be returned in XML using the SPARQL Variable Binding Results XML Format [RESULTS].

2.2 Initial Definitions

Definition: RDF Term

let I be the set of all IRIs.
let RDF-L be the set of all RDF Literals
let RDF-B be the set of all blank nodes in RDF graphs

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

This definition of RDF Term collects together several basic notions from the RDF data model.

Note that all IRIs are absolute; they may or may not include a fragment identifier [RFC3987, section 3.1]. Also note that IRIs include URIs [RFC3986] and URLs.

Definition: Query Variable

A query variable is a member of the set V where V is infinite and disjoint from RDF-T.

Queries can include blank nodes; the blank nodes in a query are disjoint from all blank nodes in the RDF graphs being matched and members of the set of variables.

Definition: Graph Pattern

A Graph Pattern is one of:

Definition: SPARQL Query

A SPARQL query is a tuple (GP, DS, SM, R) where:

The graph pattern of a query is called the query pattern.

The graph pattern may be the empty pattern. The set of solution modifiers may be the empty set.

2.3 Triple Patterns

The building blocks of queries are triple patterns. The following triple pattern has 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: Triple Pattern

A triple pattern is member of the set:
    (RDF-T union V) x (I union V) x (RDF-T union V)

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

"[The RDF core Working Group] 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."

Any SPARQL triple pattern with a literal as subject will fail to match on any RDF graph.

2.4 Pattern Solutions

Definition: Pattern Solution

Let W = V union RDF-B, the set of all variables and blank nodes.

A pattern solution is a substitution function from a subset of W to the set of RDF terms, RDF-T.

The result of replacing every member v of W in a graph pattern P by S(v) is written S(P).

If v is not in the domain of S then S(v) is defined to be v.

Definition: Query Solution

Given query Q = (GP, DS, SM, R) then S is a query solution of Q if S is a pattern solution for GP matching dataset DS.

How exactly a particular graph pattern matches a dataset is described for each kind of graph pattern in the sections below.

For example, the query:

PREFIX  dc: <http://purl.org/dc/elements/1.1/>
SELECT  ?book ?title
WHERE   { ?book dc:title ?title }

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

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

with solution:

?book ?title
<http://example.org/book/book1> "SPARQL"

2.5 Basic Graph Patterns

Definition: Basic Graph Pattern

A Basic Graph Pattern is a set of Triple Patterns.

A basic graph pattern matches on graph G with solution S if S(GP) is an RDF graph and is subgraph of G.

The SPARQL syntax uses the keyword WHERE to introduce the Query Pattern.

For a basic graph pattern to match some dataset, there must be a solution where each of the triple patterns matches the dataset with that solution.

Data:

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

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

There is a blank node [CONCEPTS] 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.

Query:

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

Query Result:

mbox
<mailto:jlow@example.com>

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

2.6 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.

Data:

@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> .

Query:

PREFIX foaf:   <http://xmlns.com/foaf/0.1/> 
SELECT ?name ?mbox
WHERE
  { ?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 provided 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> .

This is a simple, conjunctive graph pattern match, and all the variables used in the query pattern must be bound in every solution.

2.7 Blank Nodes

2.7.1 Blank Nodes and Queries

A blank node can appear in a query pattern. A blank node in a query pattern may match any RDF term.

2.7.2 Blank Nodes and Query Results

The presence of blank nodes can be indicated by labels in the serialization of query results. An application or client receiving the results of a query can tell that two solutions or two variable bindings differ in blank nodes but this information is only scoped to the results as defined in "SPARQL Variable Binding Results XML Format" or the CONSTRUCT result form.

Data:

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

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

Query:

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 blank node 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 nodes used to match the query are different in the two solutions. There is no relation between using _:a in the results and any blank node label in the data graph.

2.8 Other Syntactic Forms

There are a number of syntactic forms that abbreviate some common sequences of triples. These syntactic forms do not change the meaning of the query.

2.8.1 Predicate-Object Lists

Triple patterns with a common subject can be written so that the subject is only written once, and used for more than one triple pattern by employing the ";" notation.

    ?x  foaf:name  ?name ;
        foaf:mbox  ?mbox .

This is the same as writing the triple patterns:

    ?x  foaf:name  ?name .
    ?x  foaf:mbox  ?mbox . 

2.8.2 Object Lists

If triple patterns share both subject and predicate, then these can be written using the "," notation.

    ?x foaf:nick  "Alice" , "Alice_" .

is the same as writing the triple patterns:

   ?x  foaf:nick  "Alice" .
   ?x  foaf:nick  "Alice_" .

2.8.3 Blank Nodes

Blank nodes have labels which are scoped to the query. They are written as "_:a" for a blank node with label "a".

A blank node that is used in only one place in the query syntax can be abbreviated with []. A unique blank node will be created and used to form the triple pattern.

The [:p :v] construct can be used in triple patterns. It creates a blank node label which is used as the subject of all contained predicate-object pairs.  The created blank node can also be used in further triple patterns in the subject and object positions.

The following two forms

[ :p "v" ] .
[] :p "v" .

allocate a unique blank node label (here "b57") and are equivalent to writing:

_:b57 :p "v" .

This allocated blank node label can be used as the subject or object of further triple patterns. For example, as a subject:

[ :p "v" ] :q "w" .

is equivalent to the two triples:

_:b57 :p "v" .
_:b57 :q "w" .

and as an object:

:x :q [ :p "v" ] .

is equivalent to the two triples:

:x  :q _:b57 .
_:b57 :p "v" .

Abbreviated blank node syntax can be combined with other abbreviations for common subjects and predicates.

  [ foaf:name  ?name ;
    foaf:mbox  <alice@example.org> ]

This is the same as writing the following basic graph pattern for some uniquely allocated blank node:

  _:b18  foaf:name  ?name .
  _:b18  foaf:mbox  <alice@example.org> .

2.8.4 RDF Collections

RDF collections can be written in triple patterns using the syntax "(  )". The form () is an alternative for the IRI rdf:nil which is  http://www.w3.org/1999/02/22-rdf-syntax-ns#nil. When used with collection elements, such as (1 ?x 3) then triple patterns and blank nodes are allocated for the collection and the blank node at the head of the collection can be used as a subject or object in other triple patterns.

(1 ?x 3) :p "w" .

is a short form for:

  _:b0  :p  "w" .
  _:b0  rdf:first  1 .
  _:b0  rdf:rest   _:b1 .
  _:b1  rdf:first  ?x .
  _:b1  rdf:rest   _:b2 .
  _:b2  rdf:first  3 .
  _:b2  rdf:rest   rdf:nil .

2.8.5 Other

The keyword "a" can be used as a predicate in a triple pattern and is an alternative for the IRI rdf:type which is http://www.w3.org/1999/02/22-rdf-syntax-ns#type.

  ?x  a  :Class1 .
  [ a :appClass ] :p "v" .
  ?x    rdf:type  :Class1 .
  _:b0  rdf:type  :appClass .
  _:b0  :p        "v" .

2.9 Querying Reification Vocabulary

RDF defines reification vocabulary which provides for describing RDF statements without stating them. These descriptions of statements can be queried be using the defined vocabulary.

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix dc:  <http://purl.org/dc/elements/1.1/> .
@prefix :    <http://example/ns#> .

_:a   rdf:subject   <http://example.org/book/book1> .
_:a   rdf:predicate dc:title .
_:a   rdf:object    "SPARQL" .
_:a   :saidBy       "Alice" .

_:b   rdf:subject   <http://example.org/book/book1> .
_:b   rdf:predicate dc:title .
_:b   rdf:object    "SPARQL Tutorial" .
_:b   :saidBy       "Bob" .

In this example data, there is no RDF triple giving the title of the book; there are triples that describe two such RDF statements but the statements themselves are not asserted in the graph. A query asking for any titles of any book returns nothing.

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

SELECT ?book ?title 
WHERE
{ ?book dc:title ?title }

Query Result:

book title

There are no triples in the graph with dc:title in the property position (it appears in the object position in the data).

A query can ask about descriptions of statements made by "Bob":

PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dc:   <http://purl.org/dc/elements/1.1/>
PREFIX :     <http://example/ns#> 

SELECT ?book ?title 
WHERE
{ ?t rdf:subject    ?book  .
  ?t rdf:predicate  dc:title .
  ?t rdf:object     ?title .
  ?t :saidBy       " Bob" .
}

and there is one such description for a statement made by Bob:

book title
<http://example.org/book/book1> "SPARQL Tutorial"

3 Working with RDF Literals

An RDF Literal is written in SPARQL as a string containing the lexical form of the literal, followed by an optional language tag or an optional datatype. There are convenience forms for numeric-types literals which are of type xsd:integer, xsd:decimal, xsd:double and also for  xsd:boolean.

Examples of literal syntax in SPARQL include:

The form 1.3 as xsd:decimal is a change previosuly, it would have been an xsd:double.  The change is "in progress" to coordinate with other RDF syntaxes (N3, Turtle). If you have comments on this change, please send email to the working group comment list.

3.1 Matching RDF Literals

The data 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 .
:y   ns:p     "abc"^^dt:specialDatatype .
:z   ns:p     "cat"@en .

This RDF data is the target for query examples in the following sections.

3.1.1 Matching Integers

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

SELECT ?v WHERE { ?v ?p 42 }

3.1.2 Matching Arbitrary Datatypes

The following query has a solution with variable v being :y. The query processor does not have to have any understanding of the values in the space of the datatype because, in this case, lexical form and datatype IRI both match exactly.

SELECT ?v WHERE { ?v ?p "abc"^^<http://example.org/datatype#specialDatatype> }

3.1.3 Matching Language Tags

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

SELECT ?x WHERE { ?x ?p "cat" }

but this does find a solution where variable x is substituted by :z:

SELECT ?x WHERE { ?x ?p "cat"@en }

3.1.4 Matching with RDF D-Entailment

RDF defines D-Entailment. When matching RDF literals in graph patterns, the datatype lexical-to-value mapping may be reflected into the underlying RDF graph, leading to additional matches where it is known that two literals are the same value.

3.2 Value Constraints

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

Data:

@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 .

Query:

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

Query Result:

title price
"The Semantic Web" 23

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

3.3 Value Constraints – Definition

Definition: Value Constraint

A value constraint is a boolean-valued expression of variables and RDF Terms.

For value constraint C, a solution S matches C if S(C) is true, where S(C) is the boolean-valued expression obtained by substitution of the variables mentioned in C.

Constraints may be restrictions of the value of an RDF Term or they may be restrictions on some part of an RDF term, such as its lexical form. There is a set of functions & operators in SPARQL for constraints. In addition, there is an extension mechanism to provide access to functions that are not defined in the SPARQL language.

A constraint may lead to an error condition when testing some RDF term. The exact error will depend on the constraint: for example, in numeric operations, solutions with variables bound to a non-number or a blank node will lead to an error. Any potential solution that causes an error condition in a constraint will not form part of the final results, but does not cause the query to fail.

3.4 Matching Values and RDF D-entailment

RDF defines D-Entailment where extra semantic conditions are allowed for datatypes. RDF semantics does not require this of all RDF graphs. When matching a SPARQL query pattern against an RDF graph, there may be additional matches because of D-Entailment depending on the graph queried.

4 Graph Patterns

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

4.1 Group Graph Patterns

Definition: Group Graph Pattern

A group graph pattern GP is a set of graph patterns, GPi.

A solution of Group Graph Pattern GP on graph G is any solution S such that, for every element GPi of GP, S is a solution of GPi.

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

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

Because a solution to a group graph pattern is a solution to each element of the group, and a solution of a basic graph 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 ;
            foaf:mbox ?mbox
       }

In a SPARQL query string, a group graph pattern is delimited with braces: {}.

4.2 Unbound variables

Solutions to graph patterns do not necessarily have to have every variable bound in every solution. SPARQL query patterns are built up from basic patterns which do associate RDF terms with each variable mentioned in the pattern; OPTIONAL and UNION graph patterns can lead to query results where a variable may be bound in some solutions, but not in others.

4.3 Order of Evaluation

There is no implied order of graph patterns within a Group Graph Pattern. Any solution for the group graph pattern that can satisfy all the graph patterns in the group is valid, independently of the order that may be implied by the lexical order of the graph patterns in the group.

5 Including Optional Values

Basic graph patterns allow applications to make queries where entire 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 semi-structured: a regular, complete structure can not be assumed and it is useful to be able to have queries that allow information to be added to the solution where the information is available, but not to have the solution rejected because some part of the query pattern does not match. Optional matching provides this facility; if the 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 applied to a graph pattern:

pattern OPTIONAL { pattern }

Data:

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

_:a  rdf:type        foaf:Person .
_:a  foaf:name       "Alice" .
_:a  foaf:mbox       <mailto:alice@example.com> .
_: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>
"Alice" <mailto:alice@work.example>
"Bob"

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

This query finds the names of people in the data. If there is a triple with predicate mbox and same subject, a solution will contain 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 graph pattern must match for the optional graph pattern to add to the query solution.

5.2 Constraints in Optional Pattern Matching

Constraints can be given in an optional graph pattern as this example 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 . FILTER (?price < 30) }
        }
title price
"SPARQL Tutorial"  
"The Semantic Web" 23

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

5.3 Multiple Optional Graph Patterns

Graph patterns are defined recursively. A graph pattern may have zero or more optional graph patterns, and any part of a query pattern may have an optional part. In this example, there are two optional graph patterns.

Data:

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

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

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

Query:

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>

5.4 Optional Matching – Formal Definition

In an optional match, either an additional graph pattern matches a graph, thereby defining one or more pattern solutions; or it passes any solutions without adding any additional bindings.

Definition: Optional Graph Pattern

An optional graph pattern is a combination of a pair of graph patterns. The second pattern modifies pattern solutions of the first pattern but does not fail matching of the overall optional graph pattern.

If Opt(A, B) is an optional graph pattern, where A and B are graph patterns, then S is a solution of optional graph pattern if S is a pattern solution of A and of B otherwise if S is a solution to A, but not to A and B.

The syntactic form:

{ optional { pattern } }

is defined to be

{ } optional { pattern }

5.5 Nested Optional Graph Patterns

Optional patterns can occur inside any group graph pattern, including a group graph pattern which itself is optional, forming a nested pattern. Any non-optional part of the outer optional graph pattern must be matched if any solution is given involving matching the nested optional pattern are returned.

The outer optional graph pattern must match for any nested optional pattern to be matched.

Data:

@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@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" .

Query:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#>
SELECT ?foafName ?mbox ?gname ?fname
WHERE
  {  ?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 finds that as well.

By nesting the optional pattern involving vcard:Family, the query only reaches these if there is a vcard:N predicate. Here the expression is a simple triple pattern on vcard:N but it could be a complex graph pattern with value constraints.

6 Matching Alternatives

SPARQL provides a means of 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.

Data:

@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" .

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

_:c  dc10:title     "SPARQL" .
_:c  dc11:title     "SPARQL (updated)" .

Query:

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

SELECT ?title
WHERE  { { ?book dc10:title  ?title } UNION { ?book dc11:title  ?title } }

Query result:

title
"SPARQL Protocol Tutorial"
"SPARQL"
"SPARQL (updated)"
"SPARQL Query Language Tutorial"

This query finds titles of the books in the data, 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.0/>
PREFIX dc11:  <http://purl.org/dc/elements/1.1/>

SELECT ?x ?y
WHERE  { { ?book dc10:title ?x } UNION { ?book dc11:title  ?y } }
x y
  "SPARQL (updated)"
  "SPARQL Protocol Tutorial"
"SPARQL"  
"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 data. Note that, unlike an OPTIONAL pattern, if neither part of the UNION pattern matched, then the graph pattern would not match.

The UNION operator combines graph patterns, so 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 }
         UNION
         { ?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.2 Union Matching – Formal Definition

Definition: Union Graph Pattern

A union graph pattern is a set of graph patterns GPi.

A union graph pattern matches a graph G with solution S if there is some GPi such that GPi matches G with solution 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 graphs, comprising of triples with subject, predicate and object.  Many RDF data stores hold 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 executed against an RDF Dataset which represents such a collection of graphs. Different parts of the query may be matched against different graphs as described in the next section. There is one graph, the default graph, which does not have a name, and zero or more named graphs, each identified by IRI.

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 an IRI. Each <ui> is distinct.

G is called the default graph. (<ui>, Gi) are called named graphs.

There may be no named graphs.

A graph pattern P, where P is not an RDF Dataset Graph Pattern, matches an RDF dataset DS with solution S if P matches G (the default graph of DS) with solution S.

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

Definition: RDF Dataset Graph Pattern

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

  1. g is an IRI where g = <ui> for some i, and S is pattern solution of P on dataset {Gi, (<u1>, G1), ...}
  2. g is a variable, S maps the variable g to <ui> and S is a pattern solution of P on {Gi, (<u1>, G1), ...}

 

7.1 Examples of RDF Datasets

The definition of RDF Dataset does not restrict the relationships of named and default graphs. Two useful arrangements are:

Example 1:

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

<http://example.org/bob>    dc:publisher  "Bob" .
<http://example.org/alice>  dc:publisher  "Alice" .
# Named graph: http://example.org/bob
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

_:a foaf:name "Bob" .
_:a foaf:mbox <mailto:bob@oldcorp.example.org> .
# Named graph: http://example.org/alice
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

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

In this example, the default graph contains the names of the publishers of two named graphs. The triples in the named graphs are not visible in the default graph in this example.

Example 2:

RDF data can be combined by RDF merge[RDF-MT] of graphs so that the default graph can be made to include the RDF merge of some or all of the information in the named graphs.

In this next example, the named graphs contain the same triples as before. The RDF dataset includes an RDF merge of the named graphs in the default graph, re-labeling blank nodes to keep them distinct.

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

_:x foaf:name "Bob" .
_:x foaf:mbox <mailto:bob@oldcorp.example.org> .

_:y foaf:name "Alice" .
_:y foaf:mbox <mailto:alice@work.example.org> .
# Named graph: http://example.org/bob
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

_:a foaf:name "Bob" .
_:a foaf:mbox <mailto:bob@oldcorp.example.org> .
# Named graph: http://example.org/alice
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

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

8 Querying the Dataset

When querying a collection of graphs, the GRAPH keyword is used to match patterns against named graphs. This is by either using an IRI to select a graph or using a variable to range over the IRIs naming graphs.

The following two graphs will be used in examples:

# Named graph: http://example.org/foaf/aliceFoaf
@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> .
_:a  foaf:knows    _:b .

_:b  foaf:name     "Bob" .
_:b  foaf:mbox     <mailto:bob@work.example> .
_:b  foaf:nick     "Bobby" .
_:b  rdfs:seeAlso  <http://example.org/foaf/bobFoaf> .

<http://example.org/foaf/bobFoaf>
     rdf:type      foaf:PersonalProfileDocument .
# Named graph: http://example.org/foaf/bobFoaf
@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#> .

_:z  foaf:mbox     <mailto:bob@work.example> .
_:z  rdfs:seeAlso  <http://example.org/foaf/bobFoaf> .
_:z  foaf:nick     "Robert" .
<http://example.org/foaf/bobFoaf>
     rdf:type      foaf:PersonalProfileDocument .

8.1 Accessing Graph Names

The query below matches the graph pattern on each of the named graphs in the dataset and forms solutions which have the src variable bound to IRIs of the graph being matched.

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

SELECT ?src ?bobNick
WHERE
  {
    GRAPH ?src
    { ?x foaf:mbox <mailto:bob@work.example> .
      ?x foaf:nick ?bobNick
    }
  }

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

src bobNick
<http://example.org/foaf/aliceFoaf> "Bobby"
<http://example.org/foaf/bobFoaf> "Robert"

8.2 Restricting by Graph IRI

The query can restrict the matching applied to a specific graph by supplying the graph IRI.  This query looks for Bob's nick as given in the graph http://example.org/foaf/bobFoaf.

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

SELECT ?nick
WHERE
  {
     GRAPH data:bobFoaf {
         ?x foaf:mbox <mailto:bob@work.example> .
         ?x foaf:nick ?nick }
  }

which yields a single solution:

nick
"Robert"

8.3 Restricting by Bound Variables

A variable used in the GRAPH clause may also be used in another GRAPH clause or in a graph pattern matched against the default graph in the dataset.

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

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

SELECT ?mbox ?nick ?ppd
WHERE
{
  GRAPH data:aliceFoaf
  {
    ?alice foaf:mbox <mailto:alice@work.example> ;
           foaf:knows ?whom .
    ?whom  foaf:mbox ?mbox ;
           rdfs:seeAlso ?ppd .
    ?ppd  a foaf:PersonalProfileDocument .
  } .
  GRAPH ?ppd
  {
      ?w foaf:mbox ?mbox ;
         foaf:nick ?nick 
  }
}    
mbox nick ppd
<mailto:bob@work.example> "Robert" <http://example.org/foaf/bobFoaf>

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

8.4 Named and Default Graphs

Query patterns can involve both the default graph and the named graphs. In this example, an aggregator has read in a Web resource on two different occasions.  Each time a graph is read into the aggregator, it is given an IRI 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 IRI by the system. The RDF dataset consists of two, named graphs and the information about them.

RDF Dataset:

# Default graph
@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix g:  <tag:example.org,2005-06-06:>

g:graph1 dc:publisher "Bob" .
g:graph1 dc:date "2004-12-06"^^xsd:date .

g:graph2 dc:publisher "Bob" .
g:graph2 dc:date "2005-01-10"^^xsd:date .
# Graph: locally allocated IRI: tag:example.org,2005-06-06: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: locally allocated IRI: tag:example.org,2005-06-06: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 foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc:   <http://purl.org/dc/elements/1.1/>

SELECT ?name ?mbox ?date
WHERE
  {  ?g dc:publisher ?name ;
        dc:date ?date .
    GRAPH ?g 
      { ?person foaf:name ?name ; foaf:mbox ?mbox }
  }
The results show that the email address for "Bob" 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 IRI for the date datatype has been abbreviated in the results for clarity.

9 Specifying RDF Datasets

A SPARQL query may specify the dataset to be used for matching.  The FROM clauses give IRIs that the query processor can use to create the default graph and the FROM NAMED clause can be used to specify named graphs. The RDF dataset may also be specified in a SPARQL protocol request, in which case the protocol description overrides any description in the query itself.

A query processor may use these IRIs in any way to associate an RDF Dataset with a query. For example, it could use IRIs to retrieve documents, parse them and use the resulting triples as one of the graphs; alternatively, it might only service queries that specify IRIs of graphs that it already has stored.

The FROM and FROM NAMED keywords allow a query to specify an RDF dataset by reference; they indicate that the dataset should include graphs that are obtained from representations of the resources identified by the given IRIs (i.e. the absolute form of the given IRI references). The dataset resulting from a number of FROM and FROM NAMED clauses is:

If a query provides such a dataset description, then it is used in place of any dataset that the query service would use if no dataset description is provided in a query.

9.1 Specifying the Default Graph

The FROM clause contains an IRI that indicates the graph to be used to form the default graph. This does not automatically put the graph in as a named graph; a query can do this by also specifying the graph in the FROM NAMED clause.

In this example, there is a single default graph:

# Default graph (stored at 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
FROM    <http://example.org/foaf/aliceFoaf>
WHERE   { ?x foaf:name ?name }
name
"Alice"

If a query provides more than one FROM clause, providing more than one IRI to indicate the default graph, then the default graph is based on the RDF merge of the graphs obtained from representations of the resources identified by the given IRIs.

9.2 Specifying Named Graphs

A query can supply IRIs for the named graphs in the RDF Dataset using the FROM NAMED clause.  Each IRI is used to provide one named graph in the RDF Dataset.

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

_:a foaf:name "Bob" .
_:a foaf:mbox <mailto:bob@oldcorp.example.org> .
# Graph: http://example.org/alice
@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 ?src ?name

FROM NAMED <http://example.org/alice>
FROM NAMED <http://example.org/bob> 

WHERE
{ GRAPH ?src { ?x foaf:name ?name } }
src name
<http://example.org/bob> "Bob"
<http://example.org/alice> "Alice"

The FROM NAMED syntax suggests that the IRI identifies the corresponding graph, but actually the relationship between a URI and a graph in an RDF dataset is indirect. the IRI identifies a resource, and the resource is represented by a graph (or, more precisely: by a document that serializes a graph). For further details see [WEBARCH].

9.3 Combining FROM and FROM NAMED

The FROM clause and FROM NAMED clauses can be used in the same query.

# Default graph (stored at http://example.org/dft.ttl)
@prefix dc: <http://purl.org/dc/elements/1.1/> .

<http://example.org/bob>    dc:publisher  "Bob Hacker" .
<http://example.org/alice>  dc:publisher  "Alice Hacker" .
# Named graph: http://example.org/bob
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

_:a foaf:name "Bob" .
_:a foaf:mbox <mailto:bob@oldcorp.example.org> .
# Named graph: http://example.org/alice
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

_:a foaf:name "Alice" .
_:a foaf:mbox <mailto:alice@work.example.org> .
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>

SELECT ?who ?g ?mbox
FROM <http://example.org/dft.ttl>
FROM NAMED <http://example.org/alice>
FROM NAMED <http://example.org/bob>
WHERE
{
   ?g dc:publisher ?who .
   GRAPH ?g { ?x foaf:mbox ?mbox }
}
who g mbox
"Bob Hacker" <http://example.org/bob> <mailto:bob@oldcorp.example.org>
"Alice Hacker" <http://example.org/alice> <mailto:alice@work.example.org>

This query finds the  mbox together with the information in the default graph about the publisher. <http://example.org/dft.ttl> is just the IRI used to form the default graph, not it's name.

10 Query Result Forms

SPARQL has four query result forms. These result forms use the solutions from pattern matching to form result sets or RDF graphs. The query forms are:

SELECT
Returns all, or a subset of, the variables bound in a query pattern match.
CONSTRUCT
Returns an RDF graph constructed by substituting variables in a set of triple templates.
DESCRIBE
Returns an RDF graph that describes the resources found.
ASK
Returns a boolean indicating whether a query pattern matches or not.

The SPARQL Variable Binding Results XML Format can be used to serialize result sets from a SELECT query or the boolean result of an ASK query.

10.1 Solution Sequences and Result Forms

Query patterns generate an unordered collection of solutions, each solution being a function from variables to RDF terms. These solutions are then treated as a sequence, initially in no specific order; any sequence modifiers are then applied to create another sequence. Finally, this latter sequence is used to generate one of the SPARQL result forms.

Definition: Solution Sequence

A solution sequence S is a list of solutions.

    S = ( S1, S2, . . . , Sn)

The solution sequence from matching the query pattern is an unordered collection formed from the solutions of the query pattern.

Definition: Solution Sequence Modifier

A solution sequence modifier is one of:

If SM is set of modifiers, and QS is the collection of solutions of a query, we write SM(QS) for the sequence formed by applying SM to the solution sequence formed from QS.

Definition: Result Forms

The result form of a query is one of

The elements of a sequence of solutions can be modified by:

  1. Projection
  2. DISTINCT: ensure solutions in the sequence are unique.
  3. ORDER BY: put the solutions in order
  4. LIMIT: restrict the number of solutions processed for query results
  5. OFFSET: control where the solutions processed start from in the overall sequence of solutions.

applied in the order given by the list.

10.1.1 Projection

The solution sequence can be transformed into one involving only a subset of the variables. For each solution in the sequence, a new solution is formed using a specified selection of the variables.

Definition: Projection

The projection of solution QS over a set of variables VS is the solution
      project(QS, VS) = { (v, QS(v)) | v in VS }

For a solution sequence S = ( S1, S2, . . . , Sn) and a finite set of variables VS,
    project(S, VS) = { (project(Si, VS) | i = 1,2, . . . n }

The following example shows a query to extract just the names of people described in an RDF graph using FOAF properties.

@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@work.example> .
PREFIX foaf:       <http://xmlns.com/foaf/0.1/>
SELECT ?name 
WHERE
 { ?x foaf:name ?name }
name
"Bob"
"Alice"

10.1.2 DISTINCT

The solution sequence can be modified by adding the DISTINCT keyword which ensures that every combination of variable bindings (i.e. each solution) in the sequence is unique.

@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 }
name
"Alice"

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

Definition: Distinct Solution Sequence

A Distinct Solution Sequence has no two solutions the same.

For a solution sequence S = ( S1, S2, . . . , Sn), then write set(S) for the set of solution sequences in S.

    distinct(S) = (Si | Si != Sj for all i != j) and set(distinct(S)) = set(S)

10.1.3 ORDER BY

The ORDER BY clause takes a solution sequence and applies ordering conditions. An ordering condition can be a variable or a function call. The direction of ordering is ascending by default. It can be explicitly set to ascending or descending by enclosing the condition in ASC() or DESC() respectively. If multiple conditions are given, then they are applied in turn until one gives the indication of the ordering.

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

SELECT ?name
WHERE { ?x foaf:name ?name }
ORDER BY ?name
PREFIX     :    <http://example.org/ns#>
PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
PREFIX xsd:     <http://www.w3.org/2001/XMLSchema#>     

SELECT ?name
WHERE { ?x foaf:name ?name ; :empId ?emp }
ORDER BY DESC(?emp)
PREFIX foaf:    <http://xmlns.com/foaf/0.1/>

SELECT ?name
WHERE { ?x foaf:name ?name ; :empId ?emp }
ORDER BY ?name DESC(?emp)

Using ORDER BY on a solution sequence for a result form other than SELECT has no direct effect because only SELECT returns a sequence of results. In combination with LIMIT and OFFSET, it can be used to return partial results.

Definition: Ordered Solution Sequence

A ordered solution sequence is a solution sequence where the sequence is partially ordered with respect to some ordering condition.

A solution sequence S = ( S1, S2, . . . , Sn) is ordered with respect to an ordering condition C if, for Si, SJ, then i < j if C orders Si before Sj.

An ordering condition need not give a total ordering of a solution sequence.

The "<" operator (see the Operator Mapping Table) defines the relative order of pairs of numerics, xsd:dateTimes and xsd:strings. SPARQL defines a fixed, arbitrary order between some kinds of RDF terms that would not otherwise be ordered. This arbitrary order is necessary to provide slicing of query solutions by use of LIMIT and OFFSET.

  1. (Lowest) no value assigned to the variable or expression in this solution.
  2. Blank nodes
  3. IRIs
  4. RDF literals
  5. A plain literal before an RDF literal with type xsd:string of  the same lexical form.

IRIs are ordered by comparing the character strings making up each IRI.

If the ordering criteria do not specify the order of values, then the ordering in the solution sequence is undefined.

Ordering a sequence of solutions always results in a sequence with the same number of solutions in it, even if the ordering criteria does not differentiate between two solutions.

10.1.4 LIMIT

The LIMIT form puts an upper bound on the number of solutions returned. If the number of actual solutions is greater than the limit, then at most the limit number of solutions will be returned.

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

SELECT ?name
WHERE { ?x foaf:name ?name }
LIMIT 20

A limit of 0 would cause no results to be returned. A limit may not be negative.

Definition: Limited Solution Sequence

A Limited Solution Sequence has at most a given, fixed number of members.

The limit of solution sequence S = (S1, S2, . . . , Sn) is

limit(S,m) =
        (S1, S2, . . . , Sm) if n > m
        (S1, S2, . . . , Sn) if n <= m

10.1.5 OFFSET

OFFSET causes the solutions generated to start after the specified number of solutions. An OFFSET of zero has no effect.

The order in which solutions are returned is initially undefined. Using LIMIT and OFFSET to select different subsets of the query solutions will not be useful unless the order is made predictable by using ORDER BY.

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

SELECT  ?name
WHERE   { ?x foaf:name ?name }
ORDER BY ?name
LIMIT   5
OFFSET  10

Definition: Offset Solution Sequence

An Offset Solution Sequence with respect to another solution sequence S, is one which starts at a given index of S.

For solution sequence S = (S1, S2, . . . , Sn), the offset solution sequence
offset(S, k), k >= 0  is
     (Sk, Sk+1, . . ., Sn) if n >= k
     (), the empty sequence, if k > n

10.2 Selecting Variables

The SELECT form of results returns the variables directly. The syntax SELECT * is an abbreviation that selects all of the named 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
WHERE
  { ?x foaf:knows ?y ;
       foaf:name ?nameX .
    ?y foaf:name ?nameY .
    OPTIONAL { ?y foaf:nick ?nickY } 
  }
nameX nameY nickY
"Alice" "Bob"  
"Alice" "Clare" "CT"

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

Result sets can be accessed by the local API but also can be serialized into either XML or an RDF graph. An XML format is described in SPARQL Query Results XML Format, and this gives:

<?xml version="1.0"?>
<sparql xmlns="http://www.w3.org/2005/sparql-results#">
  <head>
    <variable name="nameX"/>
    <variable name="nameY"/>
    <variable name="nickY"/>
  </head>
  <results>
    <result>
      <binding name="nameX">
        <literal>Alice</literal>
      </binding>
      <binding name="nameY">
        <literal>Bob</literal>
      </binding>
      <binding name="nickY">
        <unbound/>
      </binding>
    </result>
    <result>
      <binding name="nameX">
        <literal>Alice</literal>
      </binding>
      <binding name="nameY">
        <literal>Clare</literal>
      </binding>
      <binding name="nickY">
        <literal>CT</literal>
      </binding>
    </result>
  </results>
</sparql>

Definition: SELECT

Given Q = (GP, DS, SM, SELECT VS) where

then, if QS is the set of solutions formed by matching dataset DS with graph pattern GP, the SELECT result is project(SM(QS), VS)

10.3 Constructing an Output Graph

The CONSTRUCT result form returns a single RDF graph specified by a graph template. The result is an RDF graph formed by taking each query solution in the solution sequence, substituting for the variables into the graph template and combining the triples into a single RDF graph by set union.

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. The graph template may contain ground or explicit triples, that is, triples with no variables, and these also appear in the RDF graph returned by the CONSTRUCT query form.

@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 from the FOAF information:
@prefix vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> .

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

10.3.1 Templates with Blank Nodes

A template can create an RDF graph containing blank nodes. The blank node labels are scoped to the template for each solution. If the same label occurs twice in a template, then there will be one blank node created for each query solution but there will be different blank nodes 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 _:v .
            _:v vcard:givenName ?gname .
            _:v vcard:familyName ?fname }
WHERE
 {
    { ?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 blank nodes (which have labels _:a and _:b in the data) causes different blank node labels (_:v1 and _:v2) as shown by the results.

10.3.2 Accessing Graphs in the RDF Dataset

Using CONSTRUCT it is possible to extract parts or the whole of graphs from the target RDF dataset. This first example returns the graph (if it is in the dataset) with IRI label http://example.org/aGraph; otherwise, it returns an empty graph.

CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/aGraph> { ?s ?p ?o } . }

The access to the graph can be conditional on other information.  Suppose the default graph contains metadata about the named graphs in the dataset, then a query like the following one can extract one graph based on information about the named graph:

PREFIX  dc: <http://purl.org/dc/elements/1.1/>
PREFIX app: <http://example.org/ns#>
CONSTRUCT { ?s ?p ?o } WHERE
 {
   GRAPH ?g { ?s ?p ?o } .
   { ?g dc:publisher <http://www.w3.org/> } .
   { ?g dc:date ?date } .
   FILTER ( app:customDate(?date) > "2005-02-28T00:00:00Z"^^xsd:dateTime ) .
 }

where app:customDate identified an extension function to turn the data format into an xsd:dateTime RDF Term.

Definition: Graph Template

A graph template is a set of triple patterns.

If T = { tj | j = 1,2 ... m } is a graph template and S is a solution then S(tj) is an RDF triple if all variables in tj are in the domain of S. S(tj) is empty otherwise.

Write S(T) for the union of S(tj).

Definition: CONSTRUCT

Let Q = (GP, DS, SM, CONSTRUCT T) where

then, if QS is the set of solutions formed by matching dataset DS with graph pattern GP, then write SM(QS) = { Si | i = 1,2 ... n }.

The CONSTRUCT result is the RDF graph formed by the RDF merge of each Si(T).

10.3.3 Solution Modifiers and CONSTRUCT

The solution modifiers of a query affect the results of a CONSTRUCT query. In this example, the output graph from the CONSTRUCT template is formed from just 2 of the solutions from graph pattern matching. The query outputs a graph with the names of the people with the top 2 sites, rated by hits.  The triples in the RDF graph are not ordered.

@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix site: <http://example.org/stats#> .

_:a foaf:name "Alice" .
_:a site:hits 2349 .

_:a foaf:name "Bob" .
_:a site:hits 105 .

_:a foaf:name "Eve" .
_:a site:hits 181 .
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX site: <http://example.org/stats#>

CONSTRUCT { [] foaf:name ?name }
WHERE
{ [] foaf:name ?name ;
     site:hits ?hits .
}
ORDER BY ?hits
LIMIT 2
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
_:x foaf:name "Bob" .
_:y foaf:name "Alice" .

10.4 Descriptions of Resources

The DESCRIBE form returns a single result RDF graph containing RDF data 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 solution, together with any resources directly named by IRI, and assembles a single RDF graph by taking a "description" from the target knowledge base. The description is determined by the query service.

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.4.1 Explicit IRIs

The DESCRIBE clause itself can take IRIs to identify the resources. The simplest DESCRIBE query is just an IRI in the DESCRIBE clause:

DESCRIBE <http://example.org/>

10.4.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 IRI or by blank node in the dataset:

PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
DESCRIBE ?x
WHERE    { ?x foaf:mbox <mailto:alice@org> }

The property foaf:mbox is defined as being an inverse function property in the FOAF vocabulary. 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/>
DESCRIBE ?x
WHERE    { ?x foaf:name "Alice" }

More than one IRI or variable can be given:

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

10.4.3 Descriptions of Resources

The RDF returned is the determined by the information publisher. It is the useful information the service has about a resource. It may include information about other resources: the RDF data for a book may also include details about the author.

A simple query such as

PREFIX ent:  <http://org.example.com/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 exOrg:  <http://org.example.com/employees#> .
@prefix rdf:    <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix owl:    <http://www.w3.org/2002/07/owl#>

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

foaf:mbox_sha1sum  rdf:type  owl:InverseFunctionalProperty .

which includes the blank node closure for the vcard vocabulary vcard:N. For a vocabulary such as FOAF, where the resources are typically blank nodes, 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.

Definition: DESCRIBE

Let Q = (GP, DS, SM, DESCRIBE V) where

then, if QS is the set of solutions formed by matching dataset DS with graph pattern GP, the DESCRIBE result is an RDF graph formed by information relating elements of
U union project(SM(QS), VS).

This definition intentionally does not proscribe the nature of the relevant information.

10.5 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/> .

_: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" }
yes

The SPARQL Query Results XML Format form of this result set gives:

<?xml version="1.0"?>
<sparql xmlns="http://www.w3.org/2005/sparql-results#">
  <head></head>
  <results>
    <boolean>true</boolean>
  </results>
</sparql>

On the same data, the following returns no match because Alice's mbox is not mentioned.

PREFIX foaf:    <http://xmlns.com/foaf/0.1/>
ASK  { ?x foaf:name  "Alice" ;
          foaf:mbox  <mailto:alice@work.example> }
no

Definition: ASK

Let Q = (GP, DS, SM, ASK) where

and QS is the set of solutions formed by matching dataset DS with graph pattern GP then the ASK result is true if SM(QS) is not empty, otherwise it is false.

11 Testing Values

SPARQL FILTERs restrict the set of solutions according to the given expression. Specifically, FILTERs eliminate any solutions that, when substituted into the expression, result in either an effective boolean value of false or produce a type error. Effective boolean values are defined in section 11.2.2 Effective Boolean Value, type error is defined in XQuery 1.0: An XML Query Language [XQUERY] section 2.3.1, Kinds of Errors.

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:decimal, xsd:double, xsd:dateTime} and types derived from xsd:decimal. The SPARQL operations are listed in table 11.1 and are associated with their productions in the grammar. In addition, SPARQL imports a subset of the XPath casting functions, listed in table 11.2, which are invokable by name within a SPARQL query. These functions and operators are taken from the XQuery 1.0 and XPath 2.0 Functions and Operators [FUNCOP].

As described above, RDF Terms are made of IRIs, Literals and Blank Nodes. RDF Literals may have datatypes in the instance data:

@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:date       "2004-12-31T19:00:00-05:00" .

_:b   a:annotates   <http://www.w3.org/TR/rdf-sparql-query/> .
_:b   dc:date       "2004-12-31T19:01:00-05:00"^^<http://www.w3.org/2001/XMLSchema#dateTime> .

The first dc:date arc has no type information. The second is tagged with the type xsd:dateTime. SPARQL operators compare the values of 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:date      ?date .
        FILTER ( ?date > "2005-01-01T00:00:00Z"^^xsd:dateTime ) }

Literals may be cast to typed literals to use the SPARQL operators.

... FILTER ( xsd:dateTime(?date) < xsd:dateTime("2005-01-01T00:00:00Z") ) ...

Namespaces:

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:, XML Schema datatypes with the prefix xsd:, and types of RDF Schema terms with the prefix rdfs:.

11.1 Operand Data Types

SPARQL defines a subset of the XPath functions and operators with operands of the following XML Schema datatypes [XSDT]:

In addition, SPARQL introduces additional operators which operate on RDF terms. The type rdfs:Literal corresponds to a Literal in the Resource Description Framework (RDF): Concepts and Abstract Syntax [CONCEPTS].

11.1.1 Type Promotion

XPath defines a set of Numeric Type Promotions. Numeric operators are defined for the following three primitive XML Schema numeric types:

These invoke XQuery's numeric type promotion to cast function arguments to the appropriate type. In summary: each of the numeric types is promoted to any type earlier in the above ordered list when used as an argument to function expecting that higher type. When an argument is promoted, the value is cast to the expected type. For instance, a "7"^^xsd:decimal will be converted to an "7.0E0"^^xsd:double when passed to an argument expecting an xsd:double. Promotion does not change the bindings of variables.

The operators defined below that take numeric arguments expect all arguments to be the same type. This is accomplished by promoting the argument with the lower type to the same type as the other argument. For example, "7"^^xsd:decimal + "6.5"^^xsd:float would call op:numeric-add("7"^^xsd:float, "6.5"^^xsd:float). In addition, any rdfs:Literal may be cast to xsd:string or xsd:numeric when used as an argument to an operator expecting that type.

XML Schema defines a set of types derived from decimal: integer; nonPositiveInteger; negativeInteger; long; int; short; byte; nonNegativeInteger; unsignedLong; unsignedInt; unsignedShort; unsignedByte and positiveInteger. These are all treated as decimals for arithmetic operations in FILTERs. SPARQL does not specifically require integrity checks on derived subtypes. SPARQL has no numeric type test operators so the distinction between a primitive type and a type derived from that primitive type is unobservable.

11.2 SPARQL Functions and Operators

SPARQL provides a subset of the functions and operators defined by XQuery Operator Mapping. XQuery 1.0 section 2.2.3 Expression Processing describes the invocation of XPath functions. The following rules accommodate the differences in the data and execution models between XQuery and SPARQL:

The logical-and and logical-or truth (T) table for true, false (F), and type error (E) is as follows:

ABA || BA && B
TTTT
TFTF
FTTF
FFFF
TETE
ETTE
FEEF
EFEF
EEEE

11.2.1 Invocation

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

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

11.2.2 Effective Boolean Value

When an operand is coerced to xsd:boolean through invoking a function that takes a xsd:boolean argument, the following rules apply:

The result is TRUE unless any of the following are true:

The XQuery Effective Boolean Value rules rely on the definition of XPath's fn:boolean, which has changed. The following rules reflect the current rules for fn:boolean applied to the argumens types present in SPARQL Queries:

[Informative: Effective boolean value is used to calcualate the arguments to the logical functions logical-and, logical-or, and fn:not, as well as evaluate the result of a filter.]

The Data Access Working Group will be asked to replace the earlier definition of EBV with this one. Please send related comments to public-rdf-dawg-comments@w3.org.

Table 11.1 Operator Mapping

The SPARQL grammar identifies a set of operators (for instance, &&, *, isIRI) used to construct constraints. The following table associates each of these grammatical productions with an operator defined by either the XQuery Operator Mapping or the additional SPARQL operators specified in section 11.2.3. When selecting the operator definition for a given set of parameters, the definition with the most specific parameters applies. For instance, when evaluating xsd:integer = xsd:signedInt, the definition for = with two numeric parameters applies, rather than the one with two RDF terms. The table is arranged so that upper-most viable candiate is the most specific.

Some of the operators are associated with nested function expressions, e.g. fn:not(op:numeric-equal(A, B)). Note that per the xpath definitions, fn:not and op:numeric-equal produce an error if their argument is an error.

When referring to type, the term numeric denotes the types xsd:integer, xsd:decimal, xsd:float, and xsd:double; the term IRI denotes a URIref in the Resource Description Framework (RDF): Concepts and Abstract Syntax [CONCEPTS]; the term Rterm denotes the types IRI, literal, and blank node; the term variable denotes a SPARQL variable; xsd types denote a typed literal with the indicated type. The names of the operators are indicated with the sop class.

SPARQL Unary Operators
Operator Type(A)FunctionResult type
XQuery Tests
! A xsd:booleanfn:not(A)xsd:boolean
+ A numericop:numeric-unary-plus(A)numeric
- A numericop:numeric-unary-minus(A)numeric
SPARQL Tests, defined in section 11.2.3
BOUND(A) variableisBound(A)xsd:boolean
isIRI(A)
isURI(A)
RtermisIRI(A)xsd:boolean
isBLANK(A) RtermisBlank(A)xsd:boolean
isLITERAL(A) RtermisLiteral(A)xsd:boolean
SPARQL Accessors
STR(A) rdf:literalstr(A)xsd:string
STR(A) IRIstr(A)xsd:string
LANG(A) rdf:literallang(A)xsd:string
DATATYPE(A) rdf:literaldatatype(A)rdfs:Datatype
SPARQL Binary Operators
Operator Type(A)Type(B)FunctionResult type
Logical Connectives
A || B xsd:booleanxsd:booleanlogical-or(A, B)xsd:boolean
A && B xsd:booleanxsd:booleanlogical-and(A, B)xsd:boolean
XPath Tests
A = B numericnumericop:numeric-equal(A, B)xsd:boolean
A = B xsd:stringxsd:stringop:numeric-equal(fn:compare(A, B), 0)xsd:boolean
A = B xsd:dateTimexsd:dateTimeop:dateTime-equal(A, B)xsd:boolean
A != B numericnumericfn:not(op:numeric-equal(A, B))xsd:boolean
A != B xsd:stringxsd:stringfn:not(op:numeric-equal(fn:compare(A, B), 0))xsd:boolean
A != B xsd:dateTimexsd:dateTimefn:not(op:dateTime-equal(A, B))xsd:boolean
A < B numericnumericop:numeric-less-than(A, B)xsd:boolean
A < B xsd:stringxsd:stringop:numeric-equal(fn:compare(A, B), -1)xsd:boolean
A < B xsd:dateTimexsd:dateTimeop:dateTime-less-than(A, B)xsd:boolean
A > B numericnumericop:numeric-greater-than(A, B)xsd:boolean
A > B xsd:stringxsd:stringop:numeric-equal(fn:compare(A, B), 1)xsd:boolean
A > B xsd:dateTimexsd:dateTimeop:dateTime-greater-than(A, B)xsd:boolean
A <= B numericnumericlogical-or(op:numeric-less-than(A, B), op:numeric-equal(A, B))xsd:boolean
A <= B xsd:stringxsd:stringfn:not(op:numeric-equal(fn:compare(A, B), 1))xsd:boolean
A <= B xsd:dateTimexsd:dateTimefn:not(op:dateTime-greater-than(A, B))xsd:boolean
A >= B numericnumericlogical-or(op:numeric-greater-than(A, B), op:numeric-equal(A, B))xsd:boolean
A >= B xsd:stringxsd:stringfn:not(op:numeric-equal(fn:compare(A, B), -1))xsd:boolean
A >= B xsd:dateTimexsd:dateTimefn:not(op:dateTime-less-than(A, B))xsd:boolean
A * B numericnumericop:numeric-multiply(A, B)numeric
A / B numericnumericop:numeric-divide(A, B)numeric; but xsd:decimal if both operands are xsd:integer
A + B numericnumericop:numeric-add(A, B)numeric
A - B numericnumericop:numeric-subtract(A, B)numeric
SPARQL Tests, defined in section 11.2.3
A = B RtermRtermRDFterm-equal(A, B)xsd:boolean
A != B RtermRtermfn:not(RDFterm-equal(A, B))xsd:boolean
langMATCHES(A, B) xsd:stringxsd:stringlangMatches(A, B)xsd:boolean
REGEX(STRING, PATTERN) xsd:stringxsd:stringfn:matches(STRING, PATTERN)xsd:boolean
SPARQL Trinary Operators
Operator Type(A)Type(B)Type(C)FunctionResult type
SPARQL Tests, defined in section 11.2.3
REGEX(STRING, PATTERN, FLAGS) xsd:stringxsd:stringxsd:stringfn:matches(STRING, PATTERN, FLAGS)xsd:boolean

11.2.3 Operators introduced in SPARQL

This section defines the operators introduced by the SPARQL Query language. The examples show the behavior of the operators as invoked by the appropriate grammatical constructs.

11.2.3.1 bound
 xsd:boolean   bound (variable var)

Returns true if a var is bound to a value. Returns false otherwise. Variables with the value NaN or INF are considered bound. See 4.2 Unbound Variables for a discussion of why variables may be unbound.

Data:

@prefix foaf:        <http://xmlns.com/foaf/0.1/> .
@prefix dc:          <http://purl.org/dc/elements/1.1/> .
@prefix xsd:          <http://www.w3.org/2001/XMLSchema#> .

_:a  foaf:givenName  "Alice".

_:b  foaf:givenName  "Bob" .
_:b  dc:date         "2005-04-04T04:04:04Z"^^xsd:dateTime .

This query finds the people without a dc:date property:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc:   <http://purl.org/dc/elements/1.1/>
PREFIX xsd:   <http://www.w3.org/2001/XMLSchema#>
SELECT ?givenName
 WHERE { ?x foaf:givenName  ?name .
         OPTIONAL { ?x dc:date ?date } .
         FILTER bound(?date) }

Query result:

givenName
"Bob"

One may test that a graph pattern is not expressed by specifying an optional graph pattern that introduces a variable and testing to see that the variable is not bound. This is called Negation as Failure in logic programming.

This query matches the people with a name but no expressed date:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc:   <http://purl.org/dc/elements/1.1/>
SELECT ?name
 WHERE { ?x foaf:givenName  ?name .
         OPTIONAL { ?x dc:date ?date } .
         FILTER (!bound(?date)) }

Query result:

name
"Alice"

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

11.2.3.2 isIRI
 xsd:boolean   isIRI (Rterm term)
 xsd:boolean   isURI (Rterm term)

Returns true if term is an IRI. Returns false otherwise. isURI is an alternate spelling for the isIRI operator.

@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       "bob@work.example" .

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

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
 WHERE { ?x foaf:name  ?name ;
            foaf:mbox  ?mbox .
         FILTER isIRI(?mbox) }

Query result:

name mbox
"Alice" <mailto:alice@work.example>
11.2.3.3 isBlank
 xsd:boolean   isBlank (Rterm term)

Returns true if term is a blank node. Returns false otherwise.

@prefix a:          <http://www.w3.org/2000/10/annotation-ns#> .
@prefix dc:         <http://purl.org/dc/elements/1.1/> .
@prefix foaf:       <http://xmlns.com/foaf/0.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 an IRI:

PREFIX a:      <http://www.w3.org/2000/10/annotation-ns#>
PREFIX dc:     <http://purl.org/dc/elements/1.1/>
PREFIX foaf:   <http://xmlns.com/foaf/0.1/>

SELECT ?given ?family
 WHERE { ?annot  a:annotates  <http://www.w3.org/TR/rdf-sparql-query/> .
         ?annot  dc:creator   ?c .
         OPTIONAL { ?c  foaf:given   ?given ; foaf:family  ?family } .
         FILTER 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 blank node.

11.2.3.4 isLiteral
 xsd:boolean   isLiteral (Rterm term)

Returns true if term is a literal. Returns false otherwise.

@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       "bob@work.example" .

This query is similar to the one in 1.2.1.3 except that is matches the people with a name and an mbox which is a Literal. This could 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 ;
           foaf:mbox  ?mbox .
         FILTER isLiteral(?mbox) }

Query result:

name mbox
"Bob" "bob@work.example"
11.2.3.5 str
 xsd:string   str (rdf:literal ltrl)
 xsd:string   str (IRI iri)

Returns the lexical form of ltrl, a literal as defined in Resource Description Framework (RDF): Concepts and Abstract Syntax [CONCEPTS] Section 6.5 "RDF Literals"; returns the codepoint representation of iri (an IRI). This is useful for examining parts of an IRI, for instance, the host-name.

@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@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 ;
            foaf:mbox  ?mbox .
         FILTER regex(str(?mbox), "@work.example") }

Query result:

name mbox
"Alice" <alice@work.example>
11.2.3.6 lang
 xsd:string   lang (rdf:literal arg)

If arg has a language tag as defined in Resource Description Framework (RDF): Concepts and Abstract Syntax [CONCEPTS] Section 6.5 "RDF Literals", lang returns the language tag of arg. It returns "" if arg is a literal with no language tag.

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

_: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 ?name ?mbox
 WHERE { ?x foaf:name  ?name ;
            foaf:mbox  ?mbox .
         FILTER ( lang(?name) = "ES" ) }

Query result:

name mbox
"Roberto"@ES <mailto:bob@work.example>
11.2.3.7 datatype
 rdfs:Datatype   datatype (rdf:literal arg)

If arg is a typed literal, as defined in Resource Description Framework (RDF): Concepts and Abstract Syntax [CONCEPTS] Section 6.5 "RDF Literals", datatype returns the datatype URI of arg. It produces a type error if arg is an untyped literal.

A plain literal is a Unicode string, which correlates to an xsd:string. There is some interest in changing the last sentence of the preceeding paragraph to

It produces a type error if arg has a language tag, and returns <xsd:string> if arg is an untyped literal without a language tag.

This would make "asdf" and "asdf"^^xsd:string indisguishable to standard SPARQL queries. Some data maintenance queries (those searching for untyped literals) would require extension functions, and all untyped literals with no language tag would follow RDF Semantics xsd:string entailment. Please send related comments to public-rdf-dawg-comments@w3.org.

@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix eg:         <http://biometrics.example/ns#> .
@prefix xsd:        <http://www.w3.org/2001/XMLSchema#> .

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

_:b  foaf:name       "bob".
_:b  eg:shoeSize     "42"^^xsd:integer .

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

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX xsd:  <http://www.w3.org/2001/XMLSchema#>
PREFIX eg:   <http://biometrics.example/ns#>
SELECT ?name ?size
 WHERE { ?x foaf:name  ?name ; eg:shoeSize  ?size .
         FILTER ( datatype(?size) = xsd:integer ) }

Query result:

name shoeSize
"Bob" 42
11.2.3.8 logical-or
 xsd:boolean   xsd:boolean left || xsd:boolean right

Returns a logical OR of left and right. As with other functions and operators with boolean arguments, logical-or operates on the effective boolean value of its arguments.

Note: see section 11.2, SPARQL Functions and Operators, for the the || operator's treatment type errors.

11.2.3.9 logical-and
 xsd:boolean   xsd:boolean left && xsd:boolean right

Returns a logical AND of left and right. As with other functions and operators with boolean arguments, logical-and operates on the effective boolean value of its arguments.

Note: see section 11.2, SPARQL Functions and Operators, for the the && operator's treatment type errors.

11.2.3.10 RDFterm-equal
 xsd:boolean   Rterm term1 = Rterm term2

Returns TRUE if term1 and term2 are the same RDF term as defined in Resource Description Framework (RDF): Concepts and Abstract Syntax [CONCEPTS]. term1 and term2 are the same if any of the following is true:

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

_: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 ;
            foaf:mbox  ?mbox1 .
         ?y foaf:name  ?name2 ;
            foaf:mbox  ?mbox2 .
         FILTER (?mbox1 = ?mbox2 && ?name1 != ?name2)
       }

Query result:

name1 name2
"Alice" "Ms A."
"Ms A." "Alice"

In this query for documents that were annotated on new years day (2004 or 2005), the RDF terms are not the same, but have equivalent values:

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

_:b   a:annotates   <http://www.w3.org/TR/rdf-sparql-query/> .
_:b   dc:date       "2004-12-31T19:00:00-05:00"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
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 ?annotates
WHERE { ?annot  a:annotates  ?annotates .
        ?annot  dc:date      ?date .
        FILTER ( ?date = xsd:dateTime("2004-01-01T00:00:00Z") || ?date = xsd:dateTime("2005-01-01T00:00:00Z") ) }
annotates
<http://www.w3.org/TR/rdf-sparql-query/>
11.2.3.11 langMatches
 xsd:boolean   langMatches (xsd:string language-range, xsd:string language-tag)

Returns true if language-range (first argument) matches language-tag (second argument) per Tags for the Identification of Languages [RFC3066] section 2.5. RFC3066 defines a case-insensitive, hierarchical matching algorithm which operates on ISO-defined subtags for language and country codes, and user defined subtags. In SPARQL, a language-range of "*" matches any non-empty language-tag string.

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

_:a  dc:title         "That Seventies Show"@en .
_:a  dc:title         "Cette Série des Années Soixante-dix"@fr .
_:a  dc:title         "Cette Série des Années Septante"@fr-BE .

This query uses langMatches and lang (described in section 11.2.3.8) to find the French titles for the show known in English as "That Seventies Show":

PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?title
 WHERE { ?x dc:title  "That Seventies Show"@en ;
            dc:title  ?title .
         FILTER ( langMatches( lang(?title), "FR" ) ) }

Query result:

title
"Cette Série des Années Soixante-dix"@fr
"Cette Série des Années Septante"@fr-BE

The idiom langMatches( lang( ?v ), "*" ) will not match literals without a language tag as lang( ?v ) will return an empty string.

11.2.3.12 regex
 xsd:boolean   regex (xsd:string text, xsd:string pattern)
 xsd:boolean   regex (xsd:string text, xsd:string pattern, xsd:string flags)

Invokes the XPath fn:matches function to match text against a regular expression pattern. The regular expression language is defined in XQuery 1.0 and XPath 2.0 Functions and Operators section 7.6.1 Regular Expression Syntax [FUNCOP]. The collation is defined in section 7.3.1 Collations.

@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 ?name
 WHERE { ?x foaf:name  ?name
         FILTER regex(?name, "^ali", "i") }

Query result:

name
"Alice"

Table 11.2 SPARQL Constructor Functions

SPARQL imports a subset of the XPath constructor functions defined in XQuery 1.0 and XPath 2.0 Functions and Operators [FUNCOP] in section 17.1 Casting from primitive types to primitive types. SPARQL constructors include all of the XPath constructors for the SPARQL operand data types plus the additional datatypes imposed by the RDF data model. Casting in SPARQL is performed by calling a constructor function for the target type on an operand of the source type. The table below summarizes the casting operations that are always allowed (Y), never allowed (N) and dependent on the lexical value (M). A casting operation from an xsd:string (the first row) to an xsd:float (the second column) is dependent on the lexical value (M).

bool = xsd:boolean
dbl = xsd:double
flt = xsd:float
dec = xsd:decimal
int = xsd:integer
dT = xsd:dateTime
str = xsd:string
IRI = IRI
ltrl = rdfs:Literal

From \ To str flt dbl dec int dT bool IRI ltrl
str Y M M M M M M Y Y
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
IRI Y N N N N N N Y Y
ltrl Y M M M M M M Y Y

11.2.4 Extensible Value Testing

An expression can also be a function call to an extension function. A function is named by an IRI, and returns an RDF term. The semantics of these functions are identified by the IRI identifying the function.

If a query request contains a function that it is not supported, the query is not executed and an error is returned.

SPARQL queries using extension functions are likely to have limited interoperability.

Syntax:

x:qname( expression, expression , ...)

Examples:

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX func: <http://example.org/functions#>
SELECT ?name ?id
WHERE { ?x foaf:name  ?name ;
           func:empId   ?id .
        FILTER func:even(?id) }
PREFIX aGeo: <http://example.org/geo#>

SELECT ?x ?y
WHERE { ?x aGeo:placeName "SWEB Town" .
        ?x aGeo:location ?xLoc .
        ?y aGeo:location ?yLoc .
        FILTER ( aGeo:distance(?xLoc, ?yLoc) < 10 ) . 
      }

A function returns an RDF term.  It might be used to test some application datatype not supported by the core SPARQL specification, it might be a transformation between datatype formats, for example into an XSD dateTime RDF term from another date format.

A. SPARQL Grammar

A SPARQL query string is a Unicode character string (c.f. section 6.1 String concepts of [CHARMOD]) 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[XML11]. Please see the "Notation" section of that specification for specific information about the notation.

In addition, the following sections apply.

A.1 IRI References

Text matched by the Q_IRI_REF production and QName (after prefix expansion) production, after escape processing, must be conform to the generic syntax of IRI references in section 2.2 of RFC 3987 "ABNF for IRI References and IRIs" [RFC3987]. For example, the Q_IRI_REF <abc#def> may occur in a SPARQL query string, but the Q_IRI_REF <abc##def> must not.

@@note constraint on prefix redeclaration from Syntax of IRI Terms.

A.2 White Space

White space (production WS) is used to separate two terminals which would otherwise be (mis-)recognized as one terminal.  White space is significant in strings, and as noted in the grammar, but otherwise white space is ignored. As a hint, rule names below in capitals indicate a possible choice of terminals.

A.3 Keywords

Keywords are matched in a case-insensitive manner.

The exception is the keyword 'a' which, in line with Turtle and N3, is used in place of the IRI rdf:type (in full,  http://www.w3.org/1999/02/22-rdf-syntax-ns#type).

A.4 Comments

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

A.5 Escape sequences in strings

Strings are used for the lexical form of RDF terms and in expressions. Within a string, the following escape sequences apply. The escape character is backslash "\"  (#x5C). No other escape sequences are defined for strings.  Names for characters given are the common names.

These escape sequences apply to all rules making up the rule for string (rules: STRING_LITERAL1, STRING_LITERAL2, STRING_LITERAL_LONG1, STRING_LITERAL_LONG2).

Escape Unicode code point
'\u' HEX HEX HEX HEX A Unicode code point in the range U+0 to U+FFFF inclusive corresponding to the encoded hexadecimal value.
'\U' HEX HEX HEX HEX HEX HEX HEX HEX A Unicode code point in the range U+10000 to U+10FFFF inclusive corresponding to the encoded hexadecimal value.
'\t' U+0009 (tab)
'\n' U+000A (line feed)
'\r' U+000D (carriage return)
'\b' U+0008 (backspace)
'\f' U+000C (form feed)
'\"' U+0022 (quotation mark, double quote mark)
"\'" U+0027 (apostrophe-quote, single quote mark)
'\\' U+005C (backslash)

where HEX is a hexadecimal character

HEX ::= [0-9] | [A-F] | [a-f]

Examples:

"abc\n"
"xy\rz"
'xy\tz'
'a\u00E9'

These escape sequences are included in the grammar below through the ECHAR rule.

A.6 Escape sequences in IRI references, prefixed names and variable names

The following escape sequences can be used in variable names, IRI references, that is, quoted IRI references, qnames and namespace prefixes.

Escape Unicode code point
'\u' HEX HEX HEX HEX A Unicode code point in the range U+0 to U+FFFF inclusive corresponding to the encoded hexadecimal value.
'\U' HEX HEX HEX HEX HEX HEX HEX HEX A Unicode code point in the range U+10000 to U+10FFFF inclusive corresponding to the encoded hexadecimal value.

Examples:

<ab\u00E9xy>
\u0041:ab\u00E9xy

These escape sequences are not included in the grammar below. Only escape sequences for characters that would be legal at that point in the grammar may be given.  For example, the variable "?x\u0020y" is not legal (\u0020 is a space and is not permitted in a variable name).

A.7 Grammar

 

[1]   Query   ::=   Prolog
( SelectQuery | ConstructQuery | DescribeQuery | AskQuery )
[2]   Prolog   ::=   BaseDecl? PrefixDecl*
[3]   BaseDecl   ::=   'BASE' Q_IRI_REF
[4]   PrefixDecl   ::=   'PREFIX' QNAME_NS Q_IRI_REF
[5]   SelectQuery   ::=   'SELECT' 'DISTINCT'? ( Var+ | '*' ) DatasetClause* WhereClause SolutionModifier
[6]   ConstructQuery   ::=   'CONSTRUCT' ConstructTemplate DatasetClause* WhereClause SolutionModifier
[7]   DescribeQuery   ::=   'DESCRIBE' ( VarOrIRIref+ | '*' ) DatasetClause* WhereClause? SolutionModifier
[8]   AskQuery   ::=   'ASK' DatasetClause* WhereClause
[9]   DatasetClause   ::=   'FROM' ( DefaultGraphClause | NamedGraphClause )
[10]   DefaultGraphClause   ::=   SourceSelector
[11]   NamedGraphClause   ::=   'NAMED' SourceSelector
[12]   SourceSelector   ::=   IRIref
[13]   WhereClause   ::=   'WHERE'? GroupGraphPattern
[14]   SolutionModifier   ::=   OrderClause? LimitClause? OffsetClause?
[15]   OrderClause   ::=   'ORDER' 'BY' OrderCondition+
[16]   OrderCondition   ::=   ( ( 'ASC' | 'DESC' ) BrackettedExpression )
| ( FunctionCall | Var | BrackettedExpression )
[17]   LimitClause   ::=   'LIMIT' INTEGER
[18]   OffsetClause   ::=   'OFFSET' INTEGER
[19]   GroupGraphPattern   ::=   '{' GraphPattern '}'
[20]   GraphPattern   ::=   Triples? ( GraphPatternNotTriples '.'? GraphPattern )?
[21]   GraphPatternNotTriples   ::=   OptionalGraphPattern | GroupOrUnionGraphPattern | GraphGraphPattern | Constraint
[22]   OptionalGraphPattern   ::=   'OPTIONAL' GroupGraphPattern
[23]   GraphGraphPattern   ::=   'GRAPH' VarOrBlankNodeOrIRIref GroupGraphPattern
[24]   GroupOrUnionGraphPattern   ::=   GroupGraphPattern ( 'UNION' GroupGraphPattern )*
[25]   Constraint   ::=   'FILTER' ( BrackettedExpression | BuiltInCall | FunctionCall )
[26]   ConstructTemplate   ::=   '{' ConstructTriples '}'
[27]   ConstructTriples   ::=   ( Triples1 ( '.' ConstructTriples )? )?
[28]   Triples   ::=   Triples1 ( '.' Triples? )?
[29]   Triples1   ::=   VarOrTerm PropertyListNotEmpty | TriplesNode PropertyList
[30]   PropertyList   ::=   PropertyListNotEmpty?
[31]   PropertyListNotEmpty   ::=   Verb ObjectList ( ';' PropertyList )?
[32]   ObjectList   ::=   GraphNode ( ',' ObjectList )?
[33]   Verb   ::=   VarOrBlankNodeOrIRIref | 'a'
[34]   TriplesNode   ::=   Collection | BlankNodePropertyList
[35]   BlankNodePropertyList   ::=   '[' PropertyListNotEmpty ']'
[36]   Collection   ::=   '(' GraphNode+ ')'
[37]   GraphNode   ::=   VarOrTerm | TriplesNode
[38]   VarOrTerm   ::=   Var | GraphTerm
[39]   VarOrIRIref   ::=   Var | IRIref
[40]   VarOrBlankNodeOrIRIref   ::=   Var | BlankNode | IRIref
[41]   Var   ::=   VAR1 | VAR2
[42]   GraphTerm   ::=   IRIref | RDFLiteral | ( '-' | '+' )? NumericLiteral | BooleanLiteral | BlankNode | NIL
[43]   Expression   ::=   ConditionalOrExpression
[44]   ConditionalOrExpression   ::=   ConditionalAndExpression ( '||' ConditionalAndExpression )*
[45]   ConditionalAndExpression   ::=   ValueLogical ( '&&' ValueLogical )*
[46]   ValueLogical   ::=   RelationalExpression
[47]   RelationalExpression   ::=   NumericExpression ( '=' NumericExpression | '!=' NumericExpression | '<' NumericExpression | '>' NumericExpression | '<=' NumericExpression | '>=' NumericExpression )?
[48]   NumericExpression   ::=   AdditiveExpression
[49]   AdditiveExpression   ::=   MultiplicativeExpression ( '+' MultiplicativeExpression | '-' MultiplicativeExpression )*
[50]   MultiplicativeExpression   ::=   UnaryExpression ( '*' UnaryExpression | '/' UnaryExpression )*
[51]   UnaryExpression   ::=     '!' PrimaryExpression
| '+' PrimaryExpression
| '-' PrimaryExpression
| PrimaryExpression
[52]   BuiltInCall   ::=     'STR' '(' Expression ')'
| 'LANG' '(' Expression ')'
| 'LANGMATCHES' '(' Expression ',' Expression ')'
| 'DATATYPE' '(' Expression ')'
| 'BOUND' '(' Var ')'
| 'isIRI' '(' Expression ')'
| 'isURI' '(' Expression ')'
| 'isBLANK' '(' Expression ')'
| 'isLITERAL' '(' Expression ')'
| RegexExpression
[53]   RegexExpression   ::=   'REGEX' '(' Expression ',' Expression ( ',' Expression )? ')'
[54]   FunctionCall   ::=   IRIref ArgList
[55]   IRIrefOrFunction   ::=   IRIref ArgList?
[56]   ArgList   ::=   ( NIL | '(' Expression ( ',' Expression )* ')' )
[57]   BrackettedExpression   ::=   '(' Expression ')'
[58]   PrimaryExpression   ::=   BrackettedExpression | BuiltInCall | IRIrefOrFunction | RDFLiteral | NumericLiteral | BooleanLiteral | BlankNode | Var
[59]   NumericLiteral   ::=   INTEGER | DECIMAL | DOUBLE
[60]   RDFLiteral   ::=   String ( LANGTAG | ( '^^' IRIref ) )?
[61]   BooleanLiteral   ::=   'true' | 'false'
[62]   String   ::=   STRING_LITERAL1 | STRING_LITERAL2 | STRING_LITERAL_LONG1 | STRING_LITERAL_LONG2
[63]   IRIref   ::=   Q_IRI_REF | QName
[64]   QName   ::=   QNAME | QNAME_NS
[65]   BlankNode   ::=   BLANK_NODE_LABEL | ANON
[66]   Q_IRI_REF   ::=   '<' ([^<>'{}|^`]-[#00-#20])* '>'
[67]   QNAME_NS   ::=   NCNAME_PREFIX? ':'
[68]   QNAME   ::=   NCNAME_PREFIX? ':' NCNAME?
[69]   BLANK_NODE_LABEL   ::=   '_:' NCNAME
[70]   VAR1   ::=   '?' VARNAME
[71]   VAR2   ::=   '$' VARNAME
[72]   LANGTAG   ::=   '@' [a-zA-Z]+ ('-' [a-zA-Z0-9]+)*
[73]   INTEGER   ::=   [0-9]+
[74]   DECIMAL   ::=   [0-9]+ '.' [0-9]* | '.' [0-9]+
[75]   DOUBLE   ::=   [0-9]+ '.' [0-9]* EXPONENT | '.' ([0-9])+ EXPONENT | ([0-9])+ EXPONENT
[76]   EXPONENT   ::=   [eE] [+-]? [0-9]+
[77]   ECHAR   ::=   '\' [tbnrf\"']
[78]   STRING_LITERAL1   ::=   "'" ( ([^#x27#x5C#xA#xD]) | ECHAR )* "'"
[79]   STRING_LITERAL2   ::=   '"' ( ([^#x22#x5C#xA#xD]) | ECHAR )* '"'
[80]   STRING_LITERAL_LONG1   ::=   "'''" ( [^'\] | ECHAR | ("'" [^']) | ("''" [^']) )* "'''"
[81]   STRING_LITERAL_LONG2   ::=   '"""' ( [^"\] | ECHAR | ('"' [^"]) | ('""' [^"]) )* '"""'
[82]   NIL   ::=   '(' WS* ')'
[83]   WS   ::=   #x20 | #x9 | #xD | #xA
[84]   ANON   ::=   '[' WS* ']'
[85]   NCCHAR1p   ::=     [A-Z]
| [a-z]
| [#x00C0-#x00D6]
| [#x00D8-#x00F6]
| [#x00F8-#x02FF]
| [#x0370-#x037D]
| [#x037F-#x1FFF]
| [#x200C-#x200D]
| [#x2070-#x218F]
| [#x2C00-#x2FEF]
| [#x3001-#xD7FF]
| [#xF900-#xFDCF]
| [#xFDF0-#xFFFD]
| [#x10000-#xEFFFF]
[86]   NCCHAR1   ::=   NCCHAR1p | '_'
[87]   VARNAME   ::=   ( NCCHAR1 | [0-9] ) ( NCCHAR1 | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] )*
[88]   NCCHAR   ::=   NCCHAR1 | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040]
[89]   NCNAME_PREFIX   ::=   NCCHAR1p ((NCCHAR|'.')* NCCHAR)?
[90]   NCNAME   ::=   NCCHAR1 ((NCCHAR|'.')* NCCHAR)?

The SPARQL grammar is LL(1) when the rules with uppercased names are used as terminals.

@@Links to generated parsers

B Conformance (DanC)

See appendix A grammar regarding conformance of _SPARQL Query strings_, and section 10 Query Result Forms for conformance of query results. See appendix E. Internet Media Type for conformance to the application/sparql-query media type.

This specification is intended for use in conjuction with the SPARQL Protocol [SPROT] and the SPARQL Query Results XML Format [RESULTS]. See those specifications for their conformance criteria.

Note that the SPARQL protocol describes an abstract interface as well as a network protocol, and the abstract interface may apply to APIs as well as network interfaces.

C. Security Considerations

SPARQL queries using FROM, FROM NAMED, or GRAPH may cause the specified URI to be dereferenced. This may cause additional use of network, disk or CPU resources along with associated secondary issues such as denial of service. The security issues of Uniform Resource Identifier (URI): Generic Syntax [RFC3986] Section 7 should be considered. In addition, the contents of file: URIs can in some cases be accessed, processed and returned as results, providing unintended access to local resources.

The SPARQL language permits extensions, which will have their own security implications.

Multiple IRIs may have the same appearance. Characters in different scripts may look similar (a Cyrillic "о" may appear similar to a Latin "o"). A character followed by combining characters may have the same visual representation as another character (LATIN SMALL LETTER E followed by COMBINING ACUTE ACCENT has the same visual representation as LATIN SMALL LETTER E WITH ACUTE). Users of SPARQL must take care to construct queries with IRIs that match the IRIs in the data. Further information about matching of similar characters can be found in Unicode Security Considerations [UNISEC] and Internationalized Resource Identifiers (IRIs) [RFC3987] Section 8.

E. Internet Media Type, File Extension and Macintosh File Type (Normative)

STATUS:
This is a draft of a possible SPARQL Query Language MIME type registration for adding to a WD. This has not been reviewed or approved by the RDF Data Access Working Group.
contact:
Eric Prud'hommeaux
See also:
How to Register a Media Type for a W3C Specification
Internet Media Type registration, consistency of use
TAG Finding 3 June 2002 (Revised 4 September 2002)

The Internet Media Type / MIME Type for the SPARQL Query Language is "application/sparql-query".

It is recommended that sparql query files have the extension ".rq" (all lowercase) on all platforms.

It is recommended that sparql query files stored on Macintosh HFS file systems be given a file type of "TEXT".

This information that follows is intended to be submitted to the IESG for review, approval, and registration with IANA.

Type name:
application
Subtype name:
sparql-query
Required parameters:
None
Optional parameters:
None
Encoding considerations:
The syntax of the SPARQL Query Language is expressed over code points in Unicode [UNICODE]. The encoding is always UTF-8 [RFC3629].
Unicode code points may also be expressed using an \uXXXX (U+0 to U+FFFF) or \UXXXXXXXX syntax (for U+10000 onwards) where X is a hexadecimal digit [0-9A-F]
Security considerations:
See SPARQL Query appendix C, Security Considerations as well as RFC 3629 [RFC3629] section 7, Security Considerations.
Interoperability considerations:
There are no known interoperability issues.
Published specification:
This specification.
Applications which use this media type:
No known applications currently use this media type.
Additional information:
Magic number(s):
A SPARQL query may have the string 'PREFIX' (case independent) near the beginning of the document.
File extension(s):
".rq"
Base URI:
The SPARQL 'BASE <IRIref>' term can change the current base URI for relative IRIrefs in the query language that are used sequentially later in the document.
Macintosh file type code(s):
"TEXT"
Person & email address to contact for further information:
public-rdf-dawg-comments@w3.org
Intended usage:
COMMON
Restrictions on usage:
None
Author/Change controller:
The SPARQL specification is a work product of the World Wide Web Consortium's RDF Data Access Working Group. The W3C has change control over these specifications.

F. References

Normative References

[CHARMOD]
Character Model for the World Wide Web 1.0: Fundamentals , R. Ishida, F. Yergeau, M. J. Düst, M. Wolf, T. Texin, Editors, W3C Recommendation, 15 February 2005, http://www.w3.org/TR/2005/REC-charmod-20050215/ . Latest version available at http://www.w3.org/TR/charmod/ .
[CONCEPTS]
Resource Description Framework (RDF): Concepts and Abstract Syntax , G. Klyne, J. J. Carroll, Editors, W3C Recommendation, 10 February 2004, http://www.w3.org/TR/2004/REC-rdf-concepts-20040210/ . Latest version available at http://www.w3.org/TR/rdf-concepts/ .
[FUNCOP]
XQuery 1.0 and XPath 2.0 Functions and Operators , J. Melton, A. Malhotra, N. Walsh, Editors, W3C Working Draft (work in progress), 4 April 2005, http://www.w3.org/TR/2005/WD-xpath-functions-20050404/ . Latest version available at http://www.w3.org/TR/xpath-functions/ .
[RDF-MT]
RDF Semantics , P. Hayes, Editor, W3C Recommendation, 10 February 2004, http://www.w3.org/TR/2004/REC-rdf-mt-20040210/ . Latest version available at http://www.w3.org/TR/rdf-mt/ .
[RFC2119]
RFC 2119 Key Words for use in RFCs to Indicate Requirement Levels, S. Bradner March 1997
[RFC3629]
RFC 3629 UTF-8, a transformation format of ISO 10646, F. Yergeau November 2003
[RFC3066]
RFC 3066 Tags for the Identification of Languages, H. Alvestrand January 2001
[RFC3986]
RFC 3986 Uniform Resource Identifier (URI): Generic Syntax, T. Berners-Lee, R. Fielding, L. Masinter January 2005
[RFC3987]
RFC 3987, "Internationalized Resource Identifiers (IRIs)", M. Dürst , M. Suignard
[UNICODE]
The Unicode Standard, Version 4. ISBN 0-321-18578-1, as updated from time to time by the publication of new versions. The latest version of Unicode and additional information on versions of the standard and of the Unicode Character Database is available at http://www.unicode.org/unicode/standard/versions/.
[XML11]
Extensible Markup Language (XML) 1.1 , J. Cowan, J. Paoli, E. Maler, C. M. Sperberg-McQueen, F. Yergeau, T. Bray, Editors, W3C Recommendation, 4 February 2004, http://www.w3.org/TR/2004/REC-xml11-20040204/ . Latest version available at http://www.w3.org/TR/xml11/ .
[XPATH20]
XML Path Language (XPath) 2.0 , M. F. Fern?dez, D. Chamberlin, M. Kay, S. Boag, J. Robie, J. Sim?n, A. Berglund, Editors, W3C Working Draft (work in progress), 4 April 2005, http://www.w3.org/TR/2005/WD-xpath20-20050404/ . Latest version available at http://www.w3.org/TR/xpath20/ .
[XQUERY]
XQuery 1.0: An XML Query Language , S. Boag, M. F. Fernández, D. Chamberlin, D. Florescu, J. Robie, J. Siméon, Editors, W3C Working Draft (work in progress), 4 April 2005, http://www.w3.org/TR/2005/WD-xquery-20050404/ . Latest version available at http://www.w3.org/TR/xquery/ .
[XSDT]
XML Schema Part 2: Datatypes Second Edition, P. V. Biron, A. Malhotra, Editors, W3C Recommendation, 28 October 2004, http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/ . Latest version available at http://www.w3.org/TR/xmlschema-2/ .

Informative References

[DC]
Expressing Simple Dublin Core in RDF/XML Dublin Core Dublin Core Metadata Initiative Recommendation 2002-07-31.
[NAMESPACE]
Namespaces in XML 1.1 , T. Bray, A. Layman, D. Hollander, R. Tobin, Editors, W3C Recommendation, 4 February 2004, http://www.w3.org/TR/2004/REC-xml-names11-20040204 . Latest version available at http://www.w3.org/TR/xml-names11/ .
[RESULTS]
SPARQL Query Results XML Format , D. Beckett, Editor, W3C Working Draft (work in progress), 27 May 2005, http://www.w3.org/TR/2005/WD-rdf-sparql-XMLres-20050527/ . Latest version available at http://www.w3.org/TR/rdf-sparql-XMLres/ .
[SPROT]
SPARQL Protocol for RDF, K. Clark, Editor, W3C Working Draft (work in progress), 27 May 2005, http://www.w3.org/TR/2005/WD-rdf-sparql-protocol-20050527/ . Latest version available at http://www.w3.org/TR/rdf-sparql-protocol/ .
[TURTLE]
"Turtle - Terse RDF Triple Language, Dave Beckett.
[UCNR]
RDF Data Access Use Cases and Requirements , K. Clark, Editor, W3C Working Draft (work in progress), 25 March 2005, http://www.w3.org/TR/2005/WD-rdf-dawg-uc-20050325/ . Latest version available at http://www.w3.org/TR/rdf-dawg-uc/ .
[UNISEC]
Unicode Security Considerations, Mark Davis, Michel Suignard
[VCARD]
Representing vCard Objects in RDF/XML W3C Note 22 February 2001 Renato Iannella. latest version is available at http://www.w3.org/TR/vcard-rdf
[WEBARCH]
Architecture of the World Wide Web, Volume One, Editors: Ian Jacobs, Norman Walsh

F. G. Acknowledgements

The SPARQL RDF Query Language is a product of the whole of the W3C RDF Data Access Working Group, and our thanks for discussions, comments and reviews go to all present and past members.

In addition, we have had comments and discussions with many people though the working group comments list.  All comments go to making a better document.  Andy would also like to particularly thank Geoff Chappell, Bob MacGregor, Yosi Scharf and Richard Newman for exploring specific issues related to SPARQL. Eric would like to acknowledge the invaluable help of Björn Höhrmann.

G. H. Change Log

In addition to the changes marked in progress using this style, changes since the 21 July 2005 Working Draft include design changes, for which the WG has or intends to have corresponding test cases:

and significant editorial changes:

Raw CVS log:

 
$Log: Overview.html,v 
Revision 1.564  2005/11/22 23:43:12  eric
~ fixing checkling errors
~ clarification of the state of the automatic invocation of EBV for boolean arguments

Revision 1.563  2005/11/22 16:39:28  connolly
cleaned up changelog in discussion with EricP

Revision 1.562  2005/11/22 16:21:34  connolly
another SOTD comment audit tweak

Revision 1.561  2005/11/22 16:20:14  connolly
more SOTD comment audit tweaks

Revision 1.560  2005/11/22 16:17:40  connolly
SOTD comment audit tweaks

Revision 1.559  2005/11/22 16:16:57  connolly
cleaning up pending comments in SOTD

Revision 1.558  2005/11/22 15:51:51  connolly
security considerations is closed

Revision 1.557  2005/11/22 15:49:48  connolly
removed redundant Unicode comment item

Revision 1.556  2005/11/22 15:18:53  eric
~ adopt DanC's proposed conformance text plus "
Note that the SPARQL protocol describes an abstract interface as well as a
network protocol, and the abstract interface may apply to APIs as well as
network interfaces.
" per irc://irc.w3.org:6665/#dawg 2005-11-22T14:58:01Z

Revision 1.555  2005/11/22 06:12:35  connolly
norm/inform audit:
 - normative: rfc3986, rfc3987, REC-rdf-mt-20040210/#collections,
   rdf-mt/#D_entailment, rdf-concepts-20040210/#section-Literals,
   rfc3629
 - informative: rdf-schema/#ch_reificationvocab,
   rdf-sparql-protocol/#specify-dataset
 - add .txt to rfcNNNN links for consistency with published IETF docs

Revision 1.554  2005/11/22 05:21:58  connolly
summarized changes
spelled bjoern's surname as he spells it

Revision 1.553  2005/11/22 04:32:54  connolly
In hopes of having the status section of the next publication
say which comments have been addressed and which haven't,
dumped a bunch of comment status stuff in the status section,

Revision 1.552  2005/11/22 00:02:56  eric
+ added DanC's Conformance text from his mail

Revision 1.551  2005/11/19 20:25:04  eric
+ added citation for Unicode (notice to WG)

Revision 1.550  2005/11/18 09:18:35  eric
- trimmed new Invocation and Effective Boolean Value issues to correspond to SPARQL's Operand Data Types

Revision 1.549  2005/11/17 23:36:32  eric
~ (editorial) validating

Revision 1.548  2005/11/17 23:31:58  eric
+ (editorial? only red text added) issue text added for the Invocation section reflecting wisdom acquired while drafting Touring XQuery
  should meet the EBV/valueTesting note in PROPOSED: to publish 1.538 + EBV/valueTesting note, plus ...

Revision 1.547  2005/11/17 16:57:01  aseaborne
Issue (i.e. red) text for double/decimal change

Revision 1.546  2005/11/17 16:10:29  aseaborne
Changes to reflect double=>decimal change on plain strings like  1.5
~ 2.1. include decimal as possible short form
~ 3    include a xsd:decimal example
~ A    Grammar updated

Revision 1.545  2005/11/17 15:28:40  eric
~ (editorial) fix feedback list name

Revision 1.544  2005/11/16 22:52:50  eric
~ (editorial) HTML validation

Revision 1.543  2005/11/16 22:50:51  eric
~ (editorial — not on approved text) s/literal/plain literal/ in the D-entailment issue in the definition of datatype per DanC's observation

Revision 1.542  2005/11/16 10:18:47  eric
~ prettied up truth table

Revision 1.541  2005/11/15 21:18:42  eric
+ DATATYPE("abc")=string? note to meet 2005-11-15T15:28:13Z <DanC_lap> PROPOSED: to publish 1.538 ...
  plus DATATYPE("abc")=string? note, plus ...

Revision 1.540  2005/11/15 15:28:53  eric
~ change the return of DATATYPE to reflect apparent concensus in DAWG telecon 2005-11-15T15:05:17Z

Revision 1.539  2005/11/15 15:27:14  eric
~ change the return of DATATYPE to reflect apparent concensus in DAWG telecon 2005-11-15T15:05:17Z

Revision 1.538  2005/11/15 14:43:55  eric
~ (editorial) well-formedness type

Revision 1.537  2005/11/15 14:33:11  eric
+ clarify the meaning of types in the Operator Mapping and function definitions
+ str, lang, datatype, and RDFterm-equal reference RDF Concepts

Revision 1.536  2005/11/14 22:20:35  eric
~ (editorial) fix RFC 3629's date per Björn Höhrmann's comment

Revision 1.535  2005/11/14 21:19:36  eric
~ s/2279/3629/g per Björn Höhrmann's comment

Revision 1.534  2005/11/14 13:41:48  eric
~ (editorial) no uses of the undeclared xs: namespace

Revision 1.533  2005/11/12 15:03:58  eric
~ (editorial) normalized Normative References

Revision 1.532  2005/11/12 14:30:49  eric
+ added substance of Conformance section per ACTION: EricP to introduce conformance section and add conformance wording where appropriate.

Revision 1.531  2005/11/11 18:40:59  eric
+ skeleton of security section
~ s/xsd:anyURI/IRI/ per conversation with DanC on IRC 2005-11-11T18:32:07Z
~ clarified type terms used in operator definitions
~ removed sop: operator prefixes and replaced them with the sop style

Revision 1.530  2005/11/11 12:05:02  aseaborne
Change in response to:

comment 2005Oct/0057

~ Text in 2.8.3 : object => subject + reword

Revision 1.527  2005/11/09 17:21:14  aseaborne
+ 3.4 D-Entailment (may need to revisit when #rdfSemantics resolved)
[Response to 
2005/Aug/0066]
~ Added numbering to all <h4> level
~ added "either" to literal description in 2.1
+ TOC to level <h4> (X.Y.Z)

Revision 1.526  2005/11/08 18:18:17  aseaborne
~ xsd:int => xsd:integer in query in 11.2.3.7

Revision 1.525  2005/11/08 17:54:53  aseaborne
+ Added 2.9 - a reification examples

Revision 1.524  2005/11/08 15:17:33  eric
~ ACTION ericP: to update sop:isIRI to include the "isuri" synonym

Revision 1.523  2005/11/07 15:27:24  aseaborne
~ 2.1.1 <code> on a keyword
~ Paragraph rewordered to put all paras dsicussing IRIs together.
~ 2.1.1 Added <h5> level headings

Revision 1.522  2005/11/04 17:04:32  aseaborne
~ 2.1.1 <code> on a keyword
~ Paragraph rewordered to put all paras dsicussing IRIs together.
~ 2.1.1 Added <h5> level headings

Revision 1.521  2005/10/30 13:30:02  eric
+ Eric's acknowledgements

Revision 1.520  2005/10/27 11:12:38  aseaborne
added acknowledgements

Revision 1.519  2005/10/27 10:43:32  aseaborne
added acknowledgements

Revision 1.518  2005/10/26 09:09:35  aseaborne
Removed redundant grammar production

Revision 1.517  2005/10/25 18:05:36  eric
~ s/ref12/CONCEPTS/ — more descriptive name for the reference.
~ s/XQuery Connectives/XQuery Tests/ — more descriptive name.
~ provisional sop:lang definition relies on RDF Concepts instead of 3066.
+ || and && links for type errors arguments.
- removed stupid line from sop:RDFterm-equal.

Revision 1.516  2005/10/25 17:16:03  aseaborne
Fix CVS log entry

Revision 1.515  2005/10/25 17:14:51  aseaborne
+ Added productions for langMatches and isIRI/isURI to grammar
~ Fixed HTML: s/<codet>/<code>/ (isLiteral)
~ Fixed HTML: CVS log for 1.514

Revision 1.514  2005/10/24 13:30:50  eric
~ section 11 layout changes per email 

Revision 1.513  2005/10/20 18:35:26  eric
~ reworked sop:langMatches to not lie.
~ clarified domain of sop:lang and sop:datatype by enumerating the types of valid input and the associated return types

Revision 1.512  2005/10/18 12:22:57  aseaborne
@@ to remember to link in generated parsers

Revision 1.511  2005/10/17 16:44:26  aseaborne
Correct reference in 2.1 to RFC 3987/3.1

Revision 1.510  2005/10/11 18:02:03  eric
~ changed sop:lang and sop:datatype per DAWG meeting 2005-10-11T15:48:08Z
~ fixed some operator argument types (! isIRI isBLANK isLITERAL) per AndyS's observations

Revision 1.509  2005/10/11 15:59:59  eric
~ changed sop:lang and sop:datatype per DAWG meeting 2005-10-11T15:48:08Z

Revision 1.508  2005/10/11 15:14:34  eric
typo

Revision 1.507  2005/10/11 15:13:15  eric
~ fixed direction of lt/gt

Revision 1.506  2005/10/11 13:42:03  eric
~ s/isIri/isURI/ -- some snuck back in but AndyS caught them.

Revision 1.505  2005/10/11 09:10:17  eric
~ clarified behavoir of sop:datatype and sop:lang (message to DAWG)

Revision 1.504  2005/10/11 08:15:30  eric
~ clarified sop:langMatches per advice from fsasaki

Revision 1.503  2005/10/10 18:31:44  eric
~ addressed TimBL's comments per 2005 Sep 13 teleconference resolution (message to DAWG)

Revision 1.502  2005/10/10 16:35:37  eric
+ sketched out langMatches design

Revision 1.501  2005/10/10 11:31:32  eric
~ updated 2.1.1 Query Term Syntax per redefining a namespace prefix and Base IRI definition

Revision 1.500  2005/10/10 10:39:43  eric
~ fixed xs: namespaces erroneously added in 1.493

Revision 1.499  2005/10/07 08:46:27  aseaborne
Remove comma in 9.2

Revision 1.498  2005/10/06 10:13:15  aseaborne
~ A.1 Added ",after escape processing,"
~ Grammar chnaged to add extra excluded characters to IRI rule.
~ Removed the comment about IRIs in the grammar itself.

Revision 1.497  2005/10/05 14:46:33  aseaborne
~ Missing [ in a ref to RFC 3987

Revision 1.496  2005/10/05 14:33:54  aseaborne
~ Removed reference to RDF URI references in 2.2

Revision 1.495  2005/09/28 12:40:01  aseaborne
~ A.1 IRI References text updated
~ Whitespace made a reference into the gramamr table

+ Section numbering in 2 and 10.
+ Ids for section 2/H4's

Revision 1.494  2005/09/27 17:15:39  aseaborne
~ Grammar update
  * Explicit tokens for '(' ')' and '[' ']'
  * BNODE_LABEL => BLANK_NODE_LABEL

Revision 1.493  2005/09/27 11:44:32  eric
- removed the "If the ordering condition is a named variable" constraint on ordering RDF literals
- literal < literal
+ xs:string < xs:string
- func-literal-less-than section
- func-literal-greater-than section

Revision 1.492  2005/09/26 13:53:51  eric
~ ordering literals depends exclusively on the < operator
+ precedence rules for the Operator Mapping Table
+ < operators et al for literals
- simplifed func-RDFterm-equal by depending on precedence in Operator Mapping Table

Revision 1.491  2005/09/23 04:06:00  eric
~ editorial: verb and article agreement, redundent adjectives
- removed unused rdf/rdfs namespace declarations in examples

Revision 1.490  2005/09/14 10:08:42  aseaborne
~ Improve IRI text in grammar section

Revision 1.489  2005/09/12 12:58:28  eric
~ editorial changes -- namespaces and normative XML Schema ref

Revision 1.488  2005/09/12 11:12:01  aseaborne
~ 2005Sep/0002 -- editorial changes

Revision 1.487  2005/09/10 05:10:36  eric
~ changed r:IRI and r:Literal to xs:anyURI and rdfs:Literal per DanC's comments (announced)

Revision 1.486  2005/09/08 17:30:44  aseaborne
Part changes from: Sep2005/0011
~ Added URI for loading default graph in comment in data for 9.1 & 9.3

Revision 1.485  2005/09/07 16:09:37  aseaborne
Part changes from: Sep2005/0011
~ 8.4 Remove urn:x-local and use tag:example.org,2005-06-06:
  in manifest default graph
~ 10.2 "?name X" ==>  ?nameX in example

Revision 1.484  2005/09/07 12:30:39  aseaborne
BNodes explicitly liek variables in defn Pattern Solution

Revision 1.483  2005/09/07 09:26:03  aseaborne
~ Editorial changes : S2005Sep/0001

Revision 1.482  2005/09/06 21:28:41  eric
~ update Query Term Syntax to respond to DanC's ammendment to clarify IRI namespace resolution

Revision 1.481  2005/09/06 21:14:28  eric
~ respond to derhoermi's comment
  (text proposed to WG)

Revision 1.480  2005/09/05 15:00:39  eric
irc://irc.w3.org/#dawg 2005-09-05T14:55:36Z <DanC> can you change eric@w3.org to public-rdf-dawg-comments@w3.org real quick, ericp?

Revision 1.479  2005/08/31 17:12:40  aseaborne
Fix links (in CVSlog)

Revision 1.478  2005/08/31 14:22:15  aseaborne
~ See 2005JulSep/0323 and 2005JulSep/0324

Revision 1.477  2005/08/31 09:57:26  aseaborne
Reset grammar (CVS problems)

Revision 1.476  2005/08/31 09:27:45  aseaborne
~ & => &amp; in MIME type registration

~ Tidied grammar

Revision 1.475  2005/08/30 13:55:17  aseaborne
grammar section: s/is is/and is/

Revision 1.474  2005/08/30 12:17:49  aseaborne
~ Fixed typo
  2005Aug/0084

Revision 1.473  2005/08/30 12:13:53  aseaborne
Typo s/must valid/must be valid/

Revision 1.472  2005/08/30 09:30:28  aseaborne
Grammar:
~ QuotedIRIRef => IRI_REF
+ text stating the grammar is LL(1)

Revision 1.471  2005/08/29 08:50:33  eric
+ integrated DaveB's mime registration text
~ renumbered Appendixes

Revision 1.470  2005/08/23 15:08:40  aseaborne
Grammar section.

Text to say IRI refs must be legal IRIs
so that <a##b> is not legal even though
the grammar rule might allow it.

Revision 1.469  2005/08/23 15:04:29  aseaborne
Grammar section.

Removed comment on ambiguity.  No longer applies.

Revision 1.468  2005/08/23 14:57:40  aseaborne
Gramm section.

~ grammar upgrade: draft LL(1) grammar; tested
  with LALR(1) (Bison) as well.
  Esacpes (\t etc) in grammar

+ Escapes \u described but not in grammar.
~ IRIRefOrFunction to be clear about the expression case.

~ Some tidying.

Revision 1.467  2005/08/16 13:56:55  eric
~ use some of DanC's words about base IRI normalization

Revision 1.466  2005/08/16 13:35:40  eric
+ clarify SPARQL QL spec about base IRI normalization per ericP's action

Revision 1.465  2005/08/16 08:13:20  eric
~ updated B Security Considerations:
  + added text from mime.txt

Revision 1.464  2005/08/10 15:51:50  aseaborne
Validation fix

Revision 1.463  2005/08/10 15:46:08  aseaborne
+ Added placeholder for acknowledgements section
~ Upgraded the text of r[:p :v] along the lines of Dave Beckett's
suggestion in 2005JulSep/0178

Revision 1.462  2005/08/10 06:47:52  eric
~ s/RFC3896/RFC3986/g
~ s/RFC3897/RFC3987/g

Revision 1.461  2005/08/10 06:37:55  eric
~ updated B Security Considerations:
  ~ reference RFC3986 (instead of 1738) for URL security considerations
  + add reference to RFC3987 for IRI security considerations

Revision 1.460  2005/08/09 15:50:47  eric
+added B Security Considerations in response to Bjoern Hoehrmann comments

Revision 1.459  2005/08/08 08:55:15  aseaborne
Didn't flush this log to previous version:

Added text to say the rules of RFC 3897/3896 apply to SPARQL.
Changed references marked as [13] and [19] to [RFC3897] and [RFC3896].

Revision 1.458  2005/08/08 08:49:51  aseaborne
+ Escape sequences (finished)
~ Validation fixes (CVS log!)

Revision 1.457  2005/08/05 21:49:22  aseaborne
Fix examples in 9.2 and 9.3

Revision 1.456  2005/08/05 15:48:29  aseaborne
Make the fact that CONSTRUCT templates can have triples (no variables) explicit

Revision 1.455  2005/08/04 13:42:59  aseaborne
Escape corrections

Revision 1.454  2005/08/04 12:51:16  aseaborne
Escape examples

Revision 1.453  2005/08/04 12:33:05  aseaborne
+ Escape sequences (finished)
~ Validation fixes (CVS log!)

Revision 1.452  2005/08/04 10:57:36  aseaborne
+ Added "_" to start of variable names
~ Tidied up by intrpducing NCCHAR1p and making NCCHAR1 be NCCHAR1p | '_'

Revision 1.451  2005/08/03 14:48:47  aseaborne
+ Added "UNICODE" to
  "A SPARQL query string is a UNICODE character string ..."

+ Escape sequences (not complete - info web site offline)

Revision 1.450  2005/08/02 11:27:49  aseaborne
Add link to protocol doc about dataset description

Revision 1.449  2005/08/01 14:03:03  aseaborne
Add text to explain [:p :q] and (1 2 3) as a subject or object
in response to 2005Jul/0053

Revision 1.448  2005/08/01 13:20:06  aseaborne
~ Use the future SPARQL query results namespace
  to http://www.w3.org/2005/sparql-results#
~ Change the published W3C Technical Report
  Version link to be the current latest version

Revision 1.447  2005/08/01 10:25:53  aseaborne
part II of v1.446

Revision 1.445  2005/07/27 17:36:40  eric
~s/isURI/isIRI/ potentially addressing Bjoern Hoehrmann's comments

Revision 1.444  2005/07/27 17:20:58  eric
~s/11.2.1.1/11.2.2/ and fixed refs

Revision 1.443  2005/07/27 16:48:03  eric
~less brutal segue from constraints to F&O ref

Revision 1.442  2005/07/27 16:38:57  eric
~rewording refs to "implementation"

Revision 1.441  2005/07/26 09:01:47  aseaborne
+ RDF colections link to
http://www.w3.org/TR/2004/REC-rdf-mt-20040210/#collections
+ Removed direct link to for URI of rdf:nil.
+ Removed direct link to for URI of rdf:type.

+ Fixed charmod reference (use &#252;)

Revision 1.440  2005/07/26 08:42:42  aseaborne
+ Referernce to charmod
+ refer to this reference in grammar sction

Revision 1.439  2005/07/25 17:19:12  aseaborne
appNS:myDataType -> appNS:appDataType

Revision 1.438  2005/07/25 14:47:57  aseaborne
Editorial in response to 2005Jul/0028
+ Sec 2.8  replace ":myClass" with ":appClass"
+ Sec 3:   "abc"^^myNS:myDataType => "abc"^^appNS:myDataType
+ Sec 10.3:
    http://example.org/myGraph => http://example.org/aGraph
    app:myDate => app:customDate
+ sec 10.4
    myOrg.example => org.example.com
    myOrg: => exOrg:

+ sec 11.2.4 Extensible Value Testing
    my: => func:
    http://my.example => http://example.org/
    myGeo: => aGeo:

Editorial in response to 2005Jul/0041
+ Fix example in 9.3: use mailto:aloce@work.example.org

Same mistake in 5.1 - fixed

Revision 1.437  2005/07/25 14:33:16  connolly
added link to XML11 from grammar section

Revision 1.436  2005/07/24 00:15:01  connolly
- class="norm" for
 - rdf-concepts (#dfn-literal etc.)
 - rdf-mt (#graphdefs, merge, etc.)
  - added [RDF-MT] at first mention
  - added bib entry
 - xquery
 - xpath-functions
 - xpath20
 - xmlschema-2
 - REC-xml11

- class="inform" for
 - rdf-dawg-uc
 - rdf-sparql-protocol
 - turtle df1/
 - rdf-sparql-XMLres
 - dublin core
 - webarch
 - vcard-rdf

- added normative ref entries for
 - RDF-MT
 - RFC 3066 (hmm... informative?)
 - XPATH20
 - XMLSCHEMA-2
 - XML11

- added informative ref entries for
 - rdf-sparql-protocol
 - unicode security considerations (hmm... normative?)
 - VCARD
 - dublin core

- replaced bogus [11] with [SPROT]

- changed RFC 3066 from faqs.org to ietf.org;
  not sure if it's informative or normative

- reformatted RFC 3986 bib entry to use cite etc.

- tweaked latest version URI of /TR/xquery/ to
  match links from the body (but differ from
  bibliography generator. hmm.)

- got rid of see also list under TOC
 - DAWG test cases link goes to status section
 - protocol, results docs become informative citations
 - punt slide set

- got rid of issues list pointer under TOC (belongs in status)

- removed one of the two "Valid XHTML!" buttons;
  added class="nav"

- truncated the CVS log at 21 July