Copyright © 2008-2026 World Wide Web Consortium. W3C® liability, trademark and permissive document license rules apply.
RDF is a directed, labeled graph data model for representing information in the Web. This specification defines the syntax and semantics of the SPARQL Query Language for RDF. SPARQL can be used to express queries across diverse data sources, whether the data is stored natively as RDF or viewed as RDF via middleware. SPARQL contains capabilities for querying required and optional graph patterns along with their conjunctions and disjunctions. SPARQL also supports aggregation, subqueries, negation, creating values by expressions, extensible value testing, and constraining queries by source RDF graph. The results of SPARQL queries can be result sets or RDF graphs.
This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C standards and drafts index.
This specification is published by the RDF Star Working Group as part of the update of specifications for format and errata.
This document was published by the RDF & SPARQL Working Group as a Working Draft using the Recommendation track.
Publication as a Working Draft does not imply endorsement by W3C and its Members.
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 a work in progress. Future updates to this upcoming Recommendation may incorporate new features.
This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent that the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This document is governed by the 18 August 2025 W3C Process Document.
RDF is a directed, labeled graph data model for representing information in the Web. RDF is often used to represent, among other things, personal information, social networks, metadata about digital artifacts, as well as to provide a means of integration over disparate sources of information. This specification defines the syntax and semantics of the SPARQL Query Language for RDF.
The SPARQL Query Language for RDF is designed to meet the use cases and requirements identified by the RDF Data Access Working Group in [RDF-DAWG-UC], the SPARQL 1.1 Working Group in [SPARQL-FEATURES], and the RDF-star Working Group.
Unless otherwise noted in the section heading, all sections and appendices in this document are normative.
This section of the document, section 1, introduces the SPARQL Query Language specification. It presents the organization of this specification document and the conventions used throughout the specification.
Section 2 of the specification introduces the SPARQL query language itself via a series of example queries and query results. Section 3 continues the introduction of the SPARQL query language with more examples that demonstrate SPARQL's ability to express constraints on the RDF terms that appear in a query's results.
Section 4 presents details of the SPARQL query language's syntax. It is a companion to the full grammar of the language and defines how grammatical constructs represent IRIs, blank nodes, literals, and variables. Section 4 also defines the meaning of several grammatical constructs that serve as syntactic sugar for more verbose expressions.
Section 5 introduces basic graph patterns and group graph patterns, the building blocks from which more complex SPARQL query patterns are constructed. Sections 6, 7, and 8 present constructs that combine SPARQL graph patterns into larger graph patterns. In particular, Section 6 introduces the ability to make portions of a query optional; Section 7 introduces the ability to express the disjunction of alternative graph patterns; and Section 8 introduces patterns to test for the absense of information.
Section 9 adds property paths to graph pattern matching, giving a compact representation of queries and also the ability to match arbitrary length paths in the graph.
Section 10 describes the forms of assignment possible in SPARQL.
Sections 11 introduces the mechanism to group and aggregate results, which can be incorporated as subqueries as described in Section 12.
Section 13 introduces the ability to constrain portions of a query to particular source graphs. Section 13 also presents SPARQL's mechanism for defining the source graphs for a query.
Section 14 refers to the separate document SPARQL 1.1 Federated Query.
Section 15 defines the constructs that affect the solutions of a query by ordering, slicing, projecting, limiting, and removing duplicates from a sequence of solutions.
Section 16 defines the four types of SPARQL queries that produce results in different forms.
Section 17 defines SPARQL's extensible value testing and expression framework. It presents the functions and operators that can be used to constrain the values that appear in a query's results and also calculate new values to be returned by a query.
Section 18 is a formal definition of the evaluation of SPARQL graph patterns and solution modifiers.
Section 19 contains the normative definition of the syntax for the SPARQL query and SPARQL 1.1 Update languages, as given by a grammar expressed in EBNF notation.
In this document, examples assume the following namespace prefix definitions unless otherwise stated:
| Prefix | IRI |
|---|---|
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# |
fn: |
http://www.w3.org/2005/xpath-functions# |
This document uses the RDF 1.1 Turtle [TURTLE] data format to show each triple explicitly. Turtle allows IRIs to be abbreviated with prefixes:
PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX : <http://example.org/book/> :book1 dc:title "SPARQL Tutorial" .
Result sets are illustrated in tabular form.
| x | y | z |
|---|---|---|
| "Alice" | <http://example/a> |
A 'binding' is a pair (variable,
RDF term).
In this result set, there are three variables:
x, y and z (shown as column headers). Each solution
is shown as one row in the body of the table. Here, there is a single solution, in
which variable x is bound to "Alice", variable y is
bound to <http://example/a>, and variable z is not bound to
an RDF term. Variables are not required to be bound in a solution.
The SPARQL language includes IRIs. Note that all IRIs in SPARQL queries are absolute; they may or may not include a fragment identifier [RFC3987], section 3.1. IRIs include URIs [RFC3986] and URLs. The abbreviated forms (relative IRIs and prefixed names) in the SPARQL syntax are resolved to produce absolute IRIs.
The following terms are defined in RDF 1.2 Concepts and Abstract Data Model [RDF12-CONCEPTS] and used in SPARQL:
Blank node identifiers are
part of
SPARQL and RDF concrete serializations.
In this document, the syntax form "_:abc" is used where the
blank node identifier
is abc. and the "_:" is
the Turtle and SPARQL syntax used to introduce blank nodes with
identifiers.
Most forms of SPARQL query contain a set of triple patterns called a basic graph pattern. Triple patterns are like RDF triples except that each of the subject, predicate and object may be a variable. A basic graph pattern matches a subgraph of the RDF data when an RDF term from that subgraph may be substituted for the variables and the result is RDF graph equivalent to the subgraph.
The example below shows a SPARQL query to find the title of a book from the given data
graph. The query consists of two parts: the SELECT clause identifies the
variables to appear in the query results, and the WHERE clause provides the
basic graph pattern to match against the data graph. The basic graph pattern in this example
consists of a single triple pattern with a single variable (?title) in the
object position.
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 .
}
This query, on the data above, has one solution:
Query Result:
| title |
|---|
| "SPARQL Tutorial" |
The result of a query is a solution sequence, corresponding to the ways in which the query's graph pattern matches the data. There may be zero, one or multiple solutions 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> . _:c foaf:mbox <mailto:carol@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> |
Each solution gives one way in which the selected variables can be bound to RDF terms so that the query pattern matches the data. The result set gives all the possible solutions. 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 basic graph pattern match; all the variables used in the query pattern must be bound in every solution.
The data below contains three 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 "cat"@en . :y ns:p "42"^^xsd:integer . :z ns:p "abc"^^dt:specialDatatype .
Note that, in Turtle, "cat"@en is an RDF literal with a lexical form "cat"
and a language tag "en"; "42"^^xsd:integer is a literal with the
datatype http://www.w3.org/2001/XMLSchema#integer; and
"abc"^^dt:specialDatatype is a literal with the datatype
http://example.org/datatype#specialDatatype.
This RDF data is the data graph for the query examples in sections 2.3.1–2.3.3.
Language tags in SPARQL are expressed using @ and the language tag, as
defined in Tags for Identifying Languages [BCP47].
This following query has no solution because "cat" is not the same RDF
literal as "cat"@en:
SELECT ?v WHERE { ?v ?p "cat" }
| v |
|---|
but the query below will find a solution where variable v is bound to
:x because the language tag is specified and matches the given data:
SELECT ?v WHERE { ?v ?p "cat"@en }
| v |
|---|
| <http://example.org/ns#x> |
Integers in a SPARQL query indicate an RDF literal with the datatype
xsd:integer. For example: 42 is a shortened form of
"42"^^<http://www.w3.org/2001/XMLSchema#integer>.
The pattern in the following query has a solution with variable v bound to
:y.
SELECT ?v WHERE { ?v ?p 42 }
| v |
|---|
| <http://example.org/ns#y> |
Section 4.1.2 defines SPARQL shortened forms for
xsd:float and xsd:double.
The following query has a solution with variable v bound to
:z. The query processor does not have to have any understanding of the values
in the space of the datatype. Because the lexical form and datatype IRI both match, the
literal matches.
SELECT ?v WHERE { ?v ?p "abc"^^<http://example.org/datatype#specialDatatype> }
| v |
|---|
| <http://example.org/ns#z> |
Query results can contain blank nodes. Blank nodes in the example result sets in this document are written in the form "_:" followed by a blank node identifier.
Blank node identifiers are scoped to a result set (see "SPARQL Query Results XML Format (Second Edition)" and
"SPARQL 1.1 Query Results JSON Format") or, for the CONSTRUCT query form, the result
graph. Use of the same identifier within a result set indicates the same blank node.
PREFIX foaf: <http://xmlns.com/foaf/0.1/> _:a foaf:name "Alice" . _:b foaf:name "Bob" .
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?x ?name
WHERE { ?x foaf:name ?name }
| x | name |
|---|---|
| _:c | "Alice" |
| _:d | "Bob" |
The results above could equally be given with different blank node identifiers because the blank node identifiers in the results only indicate whether RDF terms in the solutions are 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 need not be
any relation between a blank node identifier
_:a in the result set and a blank node identifier
used in the syntax for the data.
An application writer should not expect blank node identifiers in a query to refer to a particular blank node in the data.
SPARQL 1.2 allows values to be created from complex expressions. The queries below show how
the CONCAT function can be used to concatenate first names and
last names from FOAF data, then assign the value using an
expression in the SELECT clause and also assign the
value by using the BIND form.
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
_:a foaf:givenName "John" .
_:a foaf:surname "Doe" .
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ( CONCAT(?G, " ", ?S) AS ?name )
WHERE { ?P foaf:givenName ?G ; foaf:surname ?S }
Query:
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name
WHERE {
?P foaf:givenName ?G ;
foaf:surname ?S
BIND(CONCAT(?G, " ", ?S) AS ?name)
}
| name |
|---|
| "John Doe" |
SPARQL has several query forms. The SELECT query
form returns variable bindings. The CONSTRUCT query form returns an RDF graph.
The graph is built based on a template which is used to generate RDF triples based on the
results of matching the graph pattern of the query.
Data:
PREFIX org: <http://example.com/ns#> _:a org:employeeName "Alice" . _:a org:employeeId 12345 . _:b org:employeeName "Bob" . _:b org:employeeId 67890 .
Query:
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX org: <http://example.com/ns#>
CONSTRUCT { ?x foaf:name ?name }
WHERE { ?x org:employeeName ?name }
Results:
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
_:x foaf:name "Alice" .
_:y foaf:name "Bob" .
which can be serialized in RDF/XML as:
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="http://xmlns.com/foaf/0.1/" >
<rdf:Description>
<foaf:name>Alice</foaf:name>
</rdf:Description>
<rdf:Description>
<foaf:name>Bob</foaf:name>
</rdf:Description>
</rdf:RDF>
Graph pattern matching produces a solution sequence, where each solution has a set of
bindings of variables to RDF terms. SPARQL FILTERs restrict solutions to those for
which the filter expression evaluates to TRUE.
This section provides an informal introduction to SPARQL FILTERs; their
semantics are defined in section 'Expressions and Testing Values'
where there is a comprehensive function library. The examples in this
section share one input graph:
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 .
SPARQL FILTER functions like regex can
test RDF literals. regex matches only string
literals. regex can be used to match the lexical forms of other literals by
using the str function.
Query:
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?title
WHERE {
?x dc:title ?title
FILTER regex(?title, "^SPARQL")
}
Query Result:
| title |
|---|
| "SPARQL Tutorial" |
Regular expression matches may be made case-insensitive with the "i"
flag.
Query:
PREFIX dc: <http://purl.org/dc/elements/1.1/>
SELECT ?title
WHERE {
?x dc:title ?title
FILTER regex(?title, "web", "i" )
}
Query Result:
| title |
|---|
| "The Semantic Web" |
The regular expression language is defined by XQuery and XPath Functions and Operators and is based on XML Schema Regular Expressions.
SPARQL FILTERs can restrict on arithmetic expressions.
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.5)
?x dc:title ?title .
}
Query Result:
| title | price |
|---|---|
| "The Semantic Web" | 23 |
By constraining the price variable, only :book2 matches the query
because only :book2 has a price less than 30.5, as the filter
condition requires.
In addition to numeric types, SPARQL supports types
xsd:string, xsd:boolean and xsd:dateTime
(see Operand Data Types). Section
Operator Mapping describes the operators and
section Function Definitions describes
the functions that can be applied to RDF terms.
This section covers the syntax used by SPARQL for RDF terms and triple patterns. The full grammar is given in section 19.
The iri production designates the set of IRIs [RFC3987]; IRIs are
a generalization of URIs [RFC3986] and are fully compatible with URIs and URLs. The
PrefixedName production designates a prefixed name. The
mapping from a prefixed name to an IRI is described below. IRI references (relative or
absolute IRIs) are designated by the IRIREF production, where the
'<' and '>' delimiters do not form part of the IRI reference. Relative IRIs match the
irelative-ref reference in section 2.2 ABNF for IRI References and IRIs in
[RFC3987] and are resolved to IRIs as described below.
The PREFIX keyword associates a prefix label with an IRI. A prefixed name
is a prefix label and a local part, separated by a colon ":". A prefixed
name is mapped to an IRI by concatenating the IRI associated with the prefix and the
local part. The prefix label or the local part may be empty.
Note that SPARQL local names allow leading digits while
XML local names do not.
SPARQL local names also allow the non-alphanumeric
characters allowed in IRIs via backslash
character escapes (e.g. ns:id\=123). SPARQL local
names have more syntactic restrictions than
CURIEs.
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]) are 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 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. If
none of the above specifies the Base URI, the default Base URI (section 5.1.4, "Default
Base URI") is used.
The following fragments are some of the different ways to write the same IRI:
<http://example.org/book/book1>
BASE <http://example.org/book/> <book1>
PREFIX book: <http://example.org/book/> book:book1
The general syntax for literals is a string (enclosed in either double quotes,
"...", or single quotes, '...'), with either an optional language
tag (introduced by @) or an optional datatype IRI or prefixed name (introduced
by ^^).
As a convenience, integers can be written directly (without quotation marks and an
explicit datatype IRI) and are interpreted as literals with datatype
xsd:integer; decimal numbers for which there is '.' in the number but no
exponent are interpreted as xsd:decimal; and numbers with exponents are
interpreted as xsd:double. Values of type xsd:boolean can also be
written as true or false.
To facilitate writing literal values which themselves contain quotation marks or which are long and contain newline characters, SPARQL provides an additional quoting construct in which literals are enclosed in three single- or double-quotation marks.
Examples of literal syntax in SPARQL include:
"chat"'chat'@fr with language tag "fr""xyz"^^<http://example.org/ns/userDatatype>"abc"^^appNS:appDataType'''The librarian said, "Perhaps you would enjoy 'War and
Peace'."'''1, which is the same as "1"^^xsd:integer1.3, which is the same as "1.3"^^xsd:decimal1.300, which is the same as "1.300"^^xsd:decimal1.0e6, which is the same as "1.0e6"^^xsd:doubletrue, which is the same as "true"^^xsd:booleanfalse, which is the same as "false"^^xsd:booleanA token matching one of the productions
INTEGER,
DECIMAL,
DOUBLE or
BooleanLiteral is equivalent to a literal
with the lexical value of the token and the corresponding datatype
(xsd:integer, xsd:decimal,
xsd:double, or xsd:boolean).
A query variable is marked by the use of either "?" or "$"; the "?" or "$" is not part
of the variable name. In a query, $abc and ?abc identify the same
variable. The possible names for variables are given in the
SPARQL grammar.
Blank nodes in
graph patterns act as variables, not as references to specific blank
nodes in the data being queried. Blank nodes are indicated by
either the identifier form, such as "_:abc", or an
abbreviation form using "[]" or "[...]".
Blank node identifiers are written as "_:abc" for a
blank node with identifier "abc". The same blank node
identifier cannot be used in two different basic graph patterns in
the same query.
A blank node that is used in only one place in the query syntax can be
indicated with []. A unique blank node will be used to
form the triple pattern.
The [:p :v] construct can be used to create triple
patterns with a unique blank node as the subject of contained
predicate-object pairs.
The following two forms
[ :p "v" ] .
[] :p "v" .
allocate a unique blank node (here, illustrated by
"_:b57") and both are equivalent to writing:
_:b57 :p "v" .
The allocated blank node can be used as the subject or object of further triple patterns. For example, as a subject:
[ :p "v" ] :q "w" .
which is equivalent to the two triples:
_:b57 :p "v" . _:b57 :q "w" .
and as an object:
:x :q [ :p "v" ] .
which 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 common predicates.
[ foaf:name ?name ; foaf:mbox <mailto:alice@example.org> ]
This is the same as writing the following basic graph pattern using a blank node identifer instead.
_:b18 foaf:name ?name . _:b18 foaf:mbox <mailto:alice@example.org> .
Triple Patterns are written as subject, predicate and object; there are abbreviated ways of writing some common triple pattern constructs.
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 }
Triple patterns with a common subject can be written so that the subject is only written
once and is 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 .
If triple patterns share both subject and predicate, the objects may be separated by
",".
?x foaf:nick "Alice" , "Alice_" .
is the same as writing the triple patterns:
?x foaf:nick "Alice" . ?x foaf:nick "Alice_" .
Object lists can be combined with predicate-object lists:
?x foaf:name ?name ; foaf:nick "Alice" , "Alice_" .
is equivalent to:
?x foaf:name ?name . ?x foaf:nick "Alice" . ?x foaf:nick "Alice_" .
RDF collections can be written in triple
patterns using the syntax "(element1 element2 ...)". The form "()" is an
alternative for the IRI
http://www.w3.org/1999/02/22-rdf-syntax-ns#nil.
When used with collection elements, such as (1 ?x 3 4), triple patterns with
blank nodes are allocated for the collection. The blank node at the head of the collection
can be used as a subject or object in other triple patterns. The blank nodes allocated by
the collection syntax do not occur elsewhere in the query.
(1 ?x 3 4) :p "w" .
is syntactic sugar for (noting that b0, b1, b2
and b3 do not occur anywhere else in the query):
_:b0 rdf:first 1 ;
rdf:rest _:b1 .
_:b1 rdf:first ?x ;
rdf:rest _:b2 .
_:b2 rdf:first 3 ;
rdf:rest _:b3 .
_:b3 rdf:first 4 ;
rdf:rest rdf:nil .
_:b0 :p "w" .
RDF collections can be nested and can involve other syntactic forms:
(1 [:p :q] ( 2 ) ) .
is syntactic sugar for:
_:b0 rdf:first 1 ;
rdf:rest _:b1 .
_:b1 rdf:first _:b2 .
_:b2 :p :q .
_:b1 rdf:rest _:b3 .
_:b3 rdf:first _:b4 .
_:b4 rdf:first 2 ;
rdf:rest rdf:nil .
_:b3 rdf:rest rdf:nil .
The keyword "a" can be used as a predicate in a triple pattern and is an
alternative for the IRI
http://www.w3.org/1999/02/22-rdf-syntax-ns#type.
This keyword is case-sensitive.
?x a :Class1 . [ a :appClass ] :p "v" .
is syntactic sugar for:
?x rdf:type :Class1 . _:b0 rdf:type :appClass . _:b0 :p "v" .
To cope with the language evolution of SPARQL,
the VERSION directive can be used.
When writing SPARQL queries with new features such as
triple terms
or functions on triple terms,
authors MAY announce the use of the new syntax forms by including this directive
followed by a version label indicating the version required to process the included features.
Version labels are defined in the following section. Processors may treat unrecognized labels as an error or as a warning.
VERSION "1.2"
PREFIX : <http://example/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?s ?date {
?s ?p ?o .
BIND( <<( ?s ?p ?o )>> AS ?tt )
:myreifier rdf:reifies ?tt .
:myreifier :tripleAdded ?date .
}
A SPARQL version label is a string that identifies the syntax and semantics conformance for the SPARQL query.
Even though the version label strings in SPARQL are the same as the version labels defined by RDF, their meaning is different. Namely, the SPARQL version labels refer to SPARQL syntax and semantics, while the RDF version labels refer to RDF syntax and semantics.
| Version Label | Syntax | Semantics |
|---|---|---|
| "1.2" | SPARQL 1.2 query or update syntax | SPARQL 1.2 Query Language, SPARQL 1.2 Update |
| "1.2-basic" | SPARQL 1.2 query or update syntax, without triple terms and without triple patterns that have a triple pattern in their subject or object position | SPARQL 1.2 Query Language, SPARQL 1.2 Update |
| "1.1" | SPARQL 1.1 query or update syntax, except for use of a version directive | SPARQL 1.1 Query Language, SPARQL 1.1 Update |
If a query conforms to version "1.1", it also conforms to version "1.2-basic", and if a query conforms to version "1.2-basic", it also conforms to version "1.2".
While "1.1" is an acceptable version label,
its use in a VERSION directive is discouraged,
as it would needlessly cause SPARQL 1.1 parsers to fail.
SPARQL is based around graph pattern matching. More complex graph patterns can be formed by combining smaller patterns in various ways:
In this section we describe the two forms that combine patterns by conjunction: basic graph patterns, which combine triples patterns, and group graph patterns, which combine all other graph patterns.
The outer-most graph pattern in a query is called the query pattern. It is grammatically
identified by GroupGraphPattern in
[17] |
WhereClause |
::= | 'WHERE'? GroupGraphPattern |
Basic graph patterns are sets of triple patterns. SPARQL graph pattern matching is defined in terms of combining the results from matching basic graph patterns.
A sequence of triple patterns, with optional filters, comprises a single basic graph pattern. Any other graph pattern terminates a basic graph pattern.
When using blank nodes of the form _:abc, identifiers for blank nodes are
scoped to the basic graph pattern. A
blank node identifier
can only be used in one basic graph pattern in any query.
SPARQL evaluates basic graph patterns using subgraph matching, which is defined for simple entailment. SPARQL can be extended to other forms of entailment given certain conditions as described below. The document SPARQL 1.1 Entailment Regimes describes several specific entailment regimes.
In a SPARQL query string, a group graph pattern is delimited with braces: {}.
For example, this query's query pattern is a group graph pattern of one basic graph
pattern.
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE {
?x foaf:name ?name .
?x foaf:mbox ?mbox .
}
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?mbox
WHERE {
{ ?x foaf:name ?name . }
{ ?x foaf:mbox ?mbox . }
}
The group pattern:
{ }
matches any graph (including the empty graph) with one solution that does not bind any variables. For example:
SELECT ?x
WHERE {}
matches with one solution in which variable x is not bound.
A constraint, expressed by the keyword FILTER, is a restriction on
solutions over the whole group in which the filter appears. The following patterns all have
the same solutions:
{ ?x foaf:name ?name .
?x foaf:mbox ?mbox .
FILTER regex(?name, "Smith")
}
{ FILTER regex(?name, "Smith")
?x foaf:name ?name .
?x foaf:mbox ?mbox .
}
{ ?x foaf:name ?name .
FILTER regex(?name, "Smith")
?x foaf:mbox ?mbox .
}
{ ?x foaf:name ?name .
?x foaf:mbox ?mbox .
}
is a group of one basic graph pattern and that basic graph pattern consists of two triple patterns.
{
?x foaf:name ?name . FILTER regex(?name, "Smith")
?x foaf:mbox ?mbox .
}
is a group of one basic graph pattern and a filter, and that basic graph pattern consists of two triple patterns; the filter does not break the basic graph pattern into two basic graph patterns.
{
?x foaf:name ?name .
{}
?x foaf:mbox ?mbox .
}
is a group of three elements, a basic graph pattern of one triple pattern, an empty group, and another basic graph pattern of one triple pattern.
Basic graph patterns allow applications to make queries where the entire query pattern must match for there to be a solution. For every solution of a query containing only group graph patterns with at least one basic graph pattern, every variable is bound to an RDF Term in a solution. However, regular, complete structures cannot be assumed in all RDF graphs. It is useful to be able to have queries that allow information to be added to the solution where the information is available, but do not reject the solution because some part of the query pattern does not match. Optional matching provides this facility: if the optional part does not match, it creates no bindings but does not eliminate the solution.
Optional parts of the graph pattern may be specified syntactically with the OPTIONAL keyword applied to a graph pattern:
pattern OPTIONAL { pattern }
The syntactic form:
{ OPTIONAL { pattern } }
is equivalent to:
{ { } OPTIONAL { pattern } }
The OPTIONAL keyword is left-associative :
pattern OPTIONAL { pattern } OPTIONAL { pattern }
is the same as:
{ pattern OPTIONAL { pattern } } OPTIONAL { pattern }
In an optional match, either the optional graph pattern matches a graph, thereby defining and adding bindings to one or more solutions, or it leaves a solution unchanged without adding any additional bindings.
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".
This query finds the names of people in the data. If there is a triple with predicate
mbox and the same subject, a solution will contain the object of that triple as
well. In this example, only a single triple pattern is given in the optional match part of
the query but, in general, the optional part may be any graph pattern. The entire optional
graph pattern must match for the optional graph pattern to affect the query solution.
Constraints can be given in an optional graph pattern. For example:
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".
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.
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/>
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@work.example> |
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.
Pattern alternatives are syntactically specified with the UNION keyword.
PREFIX dc10: <http://purl.org/dc/elements/1.0/> PREFIX dc11: <http://purl.org/dc/elements/1.1/> _:a dc10:title "SPARQL Query Language Tutorial" . _:a dc10:creator "Alice" . _:b dc11:title "SPARQL Protocol Tutorial" . _:b dc11:creator "Bob" . _:c dc10:title "SPARQL" . _:c dc11:title "SPARQL (updated)" .
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. To determine exactly how the information was recorded, a query could use different variables for the two alternatives:
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" |
This will return results with the variable x bound for solutions from the
left branch of the UNION, and y bound for the solutions from the
right branch. If neither part of the UNION pattern matched, then the graph
pattern would not match.
The UNION pattern combines graph patterns; each alternative possibility can
contain more than one triple pattern:
PREFIX dc10: <http://purl.org/dc/elements/1.0/>
PREFIX dc11: <http://purl.org/dc/elements/1.1/>
SELECT ?title ?author
WHERE {
{ ?book dc10:title ?title . ?book dc10:creator ?author }
UNION
{ ?book dc11:title ?title . ?book dc11:creator ?author }
}
| title | author |
|---|---|
| "SPARQL Query Language Tutorial" | "Alice" |
| "SPARQL Protocol Tutorial" | "Bob" |
This query will only match a book if it has both a title and creator predicate from the same version of Dublin Core.
The SPARQL query language incorporates two styles of negation, one based on filtering results depending on whether a graph pattern does or does not match in the context of the query solution being filtered, and one based on removing solutions related to another pattern.
Filtering of query solutions is done within a FILTER expression using
NOT EXISTS and EXISTS. Note that the filter scope rules
apply to the whole group in which the filter appears.
The NOT EXISTS filter expression tests whether a graph pattern does not
match the dataset, given the values of variables in the group graph pattern in which the
filter occurs. It does not generate any additional bindings.
Data:
PREFIX : <http://example/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX foaf: <http://xmlns.com/foaf/0.1/> :alice rdf:type foaf:Person . :alice foaf:name "Alice" . :bob rdf:type foaf:Person .
Query:
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?person
WHERE
{
?person rdf:type foaf:Person .
FILTER NOT EXISTS { ?person foaf:name ?name }
}
Query Result:
| person |
|---|
| <http://example/bob> |
The filter expression EXISTS is also provided. It tests whether the pattern
can be found in the data; it does not generate any additional bindings.
Query:
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?person
WHERE {
?person rdf:type foaf:Person .
FILTER EXISTS { ?person foaf:name ?name }
}
Query Result:
| person |
|---|
| <http://example/alice> |
The other style of negation provided in SPARQL is MINUS which evaluates both
its arguments, then calculates solutions in the left-hand side that are not compatible with
the solutions on the right-hand side.
PREFIX : <http://example/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
:alice foaf:givenName "Alice" ;
foaf:familyName "Smith" .
:bob foaf:givenName "Bob" ;
foaf:familyName "Jones" .
:carol foaf:givenName "Carol" ;
foaf:familyName "Smith" .
PREFIX : <http://example/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT DISTINCT ?s
WHERE {
?s ?p ?o .
MINUS {
?s foaf:givenName "Bob" .
}
}
Results:
| s |
|---|
| <http://example/carol> |
| <http://example/alice> |
NOT EXISTS and MINUS represent two ways of thinking about
negation, one based on testing whether a pattern exists in the data, given the bindings
already determined by the query pattern, and one based on removing matches based on the
evaluation of two patterns. In some cases they can produce different answers.
PREFIX : <http://example/> :a :b :c .
SELECT * {
?s ?p ?o
FILTER NOT EXISTS { ?x ?y ?z }
}
evaluates to a result set with no solutions because { ?x ?y ?z } matches
given any ?s ?p ?o, so NOT EXISTS { ?x ?y ?z } eliminates any
solutions.
| s | p | o |
|---|
whereas with MINUS, there is no shared variable between the first part
(?s ?p ?o) and the second (?x ?y ?z) so no bindings are
eliminated.
SELECT * {
?s ?p ?o
MINUS
{ ?x ?y ?z }
}
Results:
| s | p | o |
|---|---|---|
| <http://example/a> | <http://example/b> | <http://example/c> |
Another case is where there is a concrete pattern (no variables) in the example:
PREFIX : <http://example/>
SELECT * {
?s ?p ?o
FILTER NOT EXISTS { :a :b :c }
}
evaluates to a result set with no query solutions:
Results:| s | p | o |
|---|
whereas
PREFIX : <http://example/>
SELECT *
{
?s ?p ?o
MINUS { :a :b :c }
}
evaluates to result set with one query solution:
Results:
| s | p | o |
|---|---|---|
| <http://example/a> | <http://example/b> | <http://example/c> |
because there is no match of bindings and so no solutions are eliminated.
Differences also arise because in a filter, variables from the group
are in scope.
In this example, the FILTER inside the
NOT EXISTS has access to the value of ?n for the solution being considered.
PREFIX : <http://example.com/> :a :p 1 . :a :q 1 . :a :q 2 . :b :p 3.0 . :b :q 4.0 . :b :q 5.0 .
When using FILTER NOT EXISTS, the test is on each possible solution to
?x :p ?n:
PREFIX : <http://example.com/>
SELECT * WHERE {
?x :p ?n
FILTER NOT EXISTS {
?x :q ?m .
FILTER(?n = ?m)
}
}
| x | n |
|---|---|
| <http://example.com/b> | 3.0 |
whereas with MINUS, the FILTER inside the pattern does not
have a value for ?n and it is always unbound:
PREFIX : <http://example/>
SELECT * WHERE {
?x :p ?n
MINUS {
?x :q ?m .
FILTER(?n = ?m)
}
}
| x | n |
|---|---|
| <http://example.com/b> | 3.0 |
| <http://example.com/a> | 1 |
A property path is a possible route through a graph between two graph nodes. A trivial case is a property path of length exactly 1, which is a triple pattern. The ends of the path may be RDF terms or variables. Variables cannot be used as part of the path itself, only the ends.
Property paths allow for more concise expressions for some SPARQL basic graph patterns and they also add the ability to match connectivity of two resources by an arbitrary length path.
In the description below, iri is either an IRI written
in full or abbreviated by a prefixed name, or the keyword a. elt
is a path element, which may itself be composed of path constructs.
| Syntax Form | Property Path Expression Name | Matches |
|---|---|---|
iri |
PredicatePath | An IRI. A path of length one. |
^elt |
InversePath | Inverse path (object to subject). |
elt1 / elt2 |
SequencePath | A sequence path of elt1 followed by elt2. |
elt1 | elt2 |
AlternativePath | A alternative path of elt1 or elt2 (all
possibilities are tried). |
elt* |
ZeroOrMorePath | A path that connects the subject and object of the path by zero or more matches of
elt. |
elt+ |
OneOrMorePath | A path that connects the subject and object of the path by one or more matches of
elt. |
elt? |
ZeroOrOnePath | A path that connects the subject and object of the path by zero or one matches of
elt. |
!iri or !(iri1|
...|irin) |
NegatedPropertySet | Negated property set. An IRI which is not one of irii.
!iri is short for !(iri). |
!^iri or !(^iri1|
...|^irin) |
NegatedPropertySet | Negated property set where the excluded matches are based on reversed path. That is, not one of iri1...irin as reverse paths. !^iri is short for !(^iri). |
!(iri1| ...|irij|^irij+1|
...|^irin) |
NegatedPropertySet | A combination of forward and reverse properties in a negated property set. |
(elt) |
A group path elt, brackets control precedence. |
The order of IRIs, and reverse IRIs, in a negated property set is not significant and they can occur in a mixed order.
The precedence of the syntax forms is, from highest to lowest:
*, ? and +/|Precedence is left-to-right within groups.
Alternatives: Match one or both possibilities
{ :book1 dc:title|rdfs:label ?displayString }
which could have written:
{
:book1 <http://purl.org/dc/elements/1.1/title> | <http://www.w3.org/2000/01/rdf-schema#label> ?displayString
}
Sequence: Find the name of any people that Alice knows.
{
?x foaf:mbox <mailto:alice@example> .
?x foaf:knows/foaf:name ?name .
}
Sequence: Find the names of people 2 "foaf:knows" links away.
{
?x foaf:mbox <mailto:alice@example> .
?x foaf:knows/foaf:knows/foaf:name ?name .
}
This is the same as the SPARQL query:
SELECT ?x ?name {
?x foaf:mbox <mailto:alice@example> .
?x foaf:knows [ foaf:knows [ foaf:name ?name ]].
}
or, with explicit variables:
SELECT ?x ?name {
?x foaf:mbox <mailto:alice@example> .
?x foaf:knows ?a1 .
?a1 foaf:knows ?a2 .
?a2 foaf:name ?name .
}
Filtering duplicates: Because someone Alice knows may well know Alice, the example above may include Alice herself. This could be avoided with:
{ ?x foaf:mbox <mailto:alice@example> .
?x foaf:knows/foaf:knows ?y .
FILTER ( ?x != ?y )
?y foaf:name ?name
}
Inverse Property Paths: These two are the same query: the second is just reversing the property direction which swaps the roles of subject and object.
{ ?x foaf:mbox <mailto:alice@example> }
{ <mailto:alice@example> ^foaf:mbox ?x }
Inverse Path Sequence: Find all the people who know someone ?x knows.
{
?x foaf:knows/^foaf:knows ?y .
FILTER(?x != ?y)
}
which is equivalent to (?gen1 is a system generated variable):
{
?x foaf:knows ?gen1 .
?y foaf:knows ?gen1 .
FILTER(?x != ?y)
}
Arbitrary length match: Find the names of all the people that can be reached from
Alice by foaf:knows:
{
?x foaf:mbox <mailto:alice@example> .
?x foaf:knows+/foaf:name ?name .
}
Alternatives in an arbitrary length path:
{ ?ancestor (ex:motherOf|ex:fatherOf)+ <#me> }
Arbitrary length path match: Some forms of limited inference are possible as well. For example, for RDFS, all types and supertypes of a resource:
{ <http://example/thing> rdf:type/rdfs:subClassOf* ?type }
All resources and all their inferred types:
{ ?x rdf:type/rdfs:subClassOf* ?type }
Subproperty:
{ ?x ?p ?v . ?p rdfs:subPropertyOf* :property }
Negated Property Paths: Find nodes connected but not by rdf:type (either way round):
{ ?x !(rdf:type|^rdf:type) ?y }
Elements in an RDF collection:
{ :list rdf:rest*/rdf:first ?element }
Note: This path expression does not guarantee the order of the results.
SPARQL property paths treat the RDF triples as a directed, possibly cyclic, graph with named edges. Evaluation of a property path expression can lead to duplicates because any variables introduced in the equivalent pattern are not part of the results and are not already used elsewhere. They are hidden by implicit projection of the results to just the variables given in the query.
For example, on the data:
PREFIX : <http://example/> :order :item :z1 . :order :item :z2 . :z1 :name "Small" . :z1 :price 5 . :z2 :name "Large" . :z2 :price 5 .
Query:
PREFIX : <http://example/>
SELECT *
{ ?s :item/:price ?x . }
Results:
| s | x |
|---|---|
| <http://example/order> | 5 |
| <http://example/order> | 5 |
whereas if the query were written out to include the intermediate variable
(?_a), no rows in the results are duplicates:
PREFIX : <http://example/>
SELECT *
{ ?s :item ?_a .
?_a :price ?x .
}
Results:
| s | _a | x |
|---|---|---|
| <http://example/order> | <http://example/z1> | 5 |
| <http://example/order> | <http://example/z2> | 5 |
The equivalence to graphs patterns is particularly significant when query also involves an aggregation operation. The total cost of the order can be found with
PREFIX : <http://example/>
SELECT (sum(?x) AS ?total) {
:order :item/:price ?x
}
| total |
|---|
| 10 |
Connectivity between the subject and object by a property path of arbitrary length can be
found using the "zero or more" property path operator, *, and the "one or more"
property path operator, +. There is also a "zero or one" connectivity property
path operator, ?.
Each of these operators uses the property path expression to try to find a connection between subject and object, using the path step a number of times, as restricted by the operator.
For example, finding all the the possible types of a resource, including supertypes of resources, can be achieved with:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?x ?type
{
?x rdf:type/rdfs:subClassOf* ?type
}
Similarly, finding all the people :x connects to via the
foaf:knows relationship,
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX : <http://example/>
SELECT ?person
{
:x foaf:knows+ ?person
}
Such connectivity matching does not introduce duplicates (it does not incorporate any count of the number of ways the connection can be made) even if the repeated path itself would otherwise result in duplicates.
The graph matched may include cycles. Connectivity matching is defined so that matching cycles does not lead to undefined or infinite results.
The value of an expression can be added to a solution mapping by binding a new variable to the value of the expression, which is an RDF term. The variable can then be used in the query and also can be returned in results.
Three syntax forms allow this: the BIND keyword,
expressions in the SELECT clause and
expressions in the GROUP BY clause. The assignment form is
(expression AS ?var).
If the evaluation of the expression produces an error, the variable remains unbound for that solution but the query evaluation continues.
Data can also be directly included in a query using
VALUES for inline data.
The BIND form allows a value to be assigned to a variable from a basic graph
pattern or property path expression. Use of BIND ends the preceding basic graph
pattern. The variable introduced by the BIND clause must not have been used in
the group graph pattern up to the point of use in BIND.
Example:
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 . :book1 ns:discount 0.2 . :book2 dc:title "The Semantic Web" . :book2 ns:price 23 . :book2 ns:discount 0.25 .
Query:
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX ns: <http://example.org/ns#>
SELECT ?title ?price
{
?x ns:price ?p .
?x ns:discount ?discount
BIND (?p*(1-?discount) AS ?price)
FILTER(?price < 20)
?x dc:title ?title .
}
Equivalent query (BIND ends the basic graph pattern; the
FILTER applies to the whole group graph pattern):
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX ns: <http://example.org/ns#>
SELECT ?title ?price
{ { ?x ns:price ?p .
?x ns:discount ?discount
BIND (?p*(1-?discount) AS ?price)
}
{?x dc:title ?title . }
FILTER(?price < 20)
}
Results:
| title | price |
|---|---|
| "The Semantic Web" | 17.25 |
Data can be directly written in a graph pattern or added to a query using
VALUES. VALUES provides inline data as a
solution sequence which are combined with the results of
query evaluation by a join operation. It can be used by an
application to provide specific requirements on query results and also by SPARQL query engine
implementations that provide federated query through the
SERVICE keyword to send a more constrained query to a remote query service.
VALUES allows multiple variables to be specified in the data block; there
is a special syntax for the common case of specifying just one variable and some
values.
In the following example, there is a table of two variables, ?x and
?y. The second row has no value for ?y.
VALUES (?x ?y) {
(:uri1 1)
(:uri2 UNDEF)
}
Optionally, when there is a single variable and some values:
VALUES ?z { "abc" "def" }
which is the same as using the general form:
VALUES (?z) { ("abc") ("def") }
Note that the same variable cannot be mentioned multiple times within the variables list of a VALUES clause.
A VALUES block of data can appear in a query pattern or at the end of a
SELECT query, including a subquery.
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 : <http://example.org/book/>
PREFIX ns: <http://example.org/ns#>
SELECT ?book ?title ?price
{
VALUES ?book { :book1 :book3 }
?book dc:title ?title ;
ns:price ?price .
}
Result:
| book | title | price |
|---|---|---|
| <http://example.org/book/book1> | "SPARQL Tutorial" | 42 |
If a variable has no value for a particular solution in the VALUES clause,
the keyword UNDEF is used instead of an RDF term.
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX : <http://example.org/book/>
PREFIX ns: <http://example.org/ns#>
SELECT ?book ?title ?price
{
?book dc:title ?title ;
ns:price ?price .
VALUES (?book ?title) {
(UNDEF "SPARQL Tutorial")
(:book2 UNDEF)
}
}
| book | title | price |
|---|---|---|
| <http://example.org/book/book1> | "SPARQL Tutorial" | 42 |
| <http://example.org/book/book2> | "The Semantic Web" | 23 |
In this example, the VALUES might have been specified to execute over the
results of the SELECT query:
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX : <http://example.org/book/>
PREFIX ns: <http://example.org/ns#>
SELECT ?book ?title ?price {
?book dc:title ?title ;
ns:price ?price .
}
VALUES (?book ?title) {
(UNDEF "SPARQL Tutorial")
(:book2 UNDEF)
}
This is a different query but, in the example situation, has the same results.
Aggregates apply expressions over groups of solutions. By default a solution set consists of a single group, containing all solutions.
Grouping may be specified using the GROUP BY syntax.
Aggregates defined in version 1.1 of SPARQL are COUNT, SUM,
MIN, MAX, AVG, GROUP_CONCAT, and
SAMPLE.
Aggregates are used where the querier wishes to see a result which is computed over a group of solutions, rather than a single solution. For example the maximum value that a particular variable takes, rather than each value individually.
Data:
PREFIX : <http://books.example/> :org1 :affiliates :auth1, :auth2 . :auth1 :writesBook :book1, :book2 . :book1 :price 9 . :book2 :price 5 . :auth2 :writesBook :book3 . :book3 :price 7 . :org2 :affiliates :auth3 . :auth3 :writesBook :book4 . :book4 :price 7 .
Query:
PREFIX : <http://books.example/>
SELECT (SUM(?lprice) AS ?totalPrice)
WHERE {
?org :affiliates ?auth .
?auth :writesBook ?book .
?book :price ?lprice .
}
GROUP BY ?org
HAVING (SUM(?lprice) > 10)
Results:
| totalPrice |
|---|
| 21 |
This example demonstrates two features of aggregates: GROUP BY, which groups
query solutions according to one or more expressions (in this case ?org), and
HAVING, which is analogous to a FILTER expression, but operates
over groups, rather than individual solutions.
The example is produced by grouping solutions according to the GROUP BY
expression (i.e. all solutions where ?org takes a particular value appear within
the same group), and evaluating the Set Function SUM over that group. The groups
are then filtered by the HAVING expression, which removes all groups where
SUM(?lprice) is not greater than 10.
In aggregate queries and sub-queries, variables that appear in the query pattern, but are
not in the GROUP BY clause, can only be projected or used in select expressions
if they are aggregated. The SAMPLE aggregate may be used for this purpose. For
details see the section on Projection Restrictions.
It should be noted that as per functions, aggregate
expressions are required to be aliased (again, similar to the BIND clause, using
the keyword AS) in order to project them from queries or subqueries. In the
example above this is done using the variable ?totalPrice. It is an error for
aggregates to project variables with a name already used in other aggregate projections, or
in the WHERE clause.
In order to calculate aggregate values for a solution, the solution is first divided into one or more groups, and the aggregate value is calculated for each group.
If aggregates are used in the query level in SELECT, HAVING or
ORDER BY but the GROUP BY term is not used, then this is taken to
be a single implicit group, to which all solutions belong.
Within GROUP BY clauses the binding keyword, AS, may be used,
such as GROUP BY (?x + ?y AS ?z). This is equivalent to
{ ... BIND (?x + ?y AS ?z) } GROUP BY ?z.
For example, given a solution sequence S, ( {?x→2, ?y→3}, {?x→2, ?y→5}, {?x→6, ?y→7} ), we
might wish to group the solutions according to the value of ?x, and calculate the average of
the values of ?y for each group.
This could be written as:
SELECT (AVG(?y) AS ?avg)
WHERE {
?a :x ?x ;
:y ?y .
}
GROUP BY ?x
HAVING operates over grouped solution sets, in the same way that
FILTER operates over un-grouped ones.
HAVING expressions have the same evaluation rules as projections from grouped
queries, as described in the following section.
An example of the use of HAVING is given below.
PREFIX : <http://data.example/>
SELECT (AVG(?size) AS ?asize)
WHERE {
?x :size ?size
}
GROUP BY ?x
HAVING(AVG(?size) > 10)
This will return average sizes, grouped by the subject, but only where the mean size is greater than 10.
In a query level which uses grouping (either by the explicit use of a GROUP BY clause
or through the use of aggregates in projection, HAVING, or ORDER BY clauses),
every occurrence of a variable that appears in projection or SELECT expressions of that query level
MUST satisfy one of the following conditions:
GROUP BY variable (with the corresponding GROUP BY expression consisting of just the variable V, or having the form (expr AS V))MIN(?v) or AVG(?v+2))
If such a variable occurrence does not satisfy one of these conditions, the query is syntactically invalid.
For example, the following query is legal as ?x is given as a GROUP BY
term.
PREFIX : <http://example.com/data/#>
SELECT ?x (MIN(?y) * 2 AS ?min)
WHERE {
?x :p ?y .
?x :q ?z .
} GROUP BY ?x (STR(?z))
Note that it would not be legal to project STR(?z) as this expression is neither a simple variable,
nor a named GROUP BY expression. However, with GROUP BY ?x (STR(?z) AS ?strZ) it would b[Truncated]