SPARQL 1.1 Query Language @import url("local.css");
code { font-family: monospace; }
div.constraint, div.issue, div.note, div.notice { margin-left: 2em; }
ol.enumar { list-style-type: decimal; } ol.enumla { list-style-type: lower-alpha; } ol.enumlr { list-style-type: lower-roman; } ol.enumua { list-style-type: upper-alpha; } ol.enumur { list-style-type: upper-roman; }
div.exampleInner pre { margin-left: 1em; margin-top: 0em; margin-bottom: 0em} div.exampleOuter {border: 4px double gray; margin: 0em; padding: 0em} div.exampleInner { background-color: #d5dee3; border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; border-bottom-width: 4px; border-bottom-style: double; border-bottom-color: #d3d3d3; padding: 4px; margin: 0em } div.exampleWrapper { margin: 4px } div.exampleHeader { font-weight: bold; margin: 4px}
em.rfc2119 { text-transform: lowercase; font-variant: small-caps; font-style: normal; } This version: http://www.w3.org/TR/2013/REC-sparql11-query-20130321/ Latest version: http://www.w3.org/TR/sparql11-query/ Previous version: http://www.w3.org/TR/2012/PR-sparql11-query-20121108/ Editors: Steve Harris, Garlik, a part of Experian Andy Seaborne, The Apache Software Foundation Previous Editor: Eric Prud'hommeaux, W3C Please refer to the errata See also translations Copyright W3C ® MIT ERCIM Keio Beihang liability trademark document use RDF is a directed, labeled graph data format 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. May Be Superseded 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 Set of Documents This document is one of eleven SPARQL 1.1 Recommendations produced by the SPARQL Working Group SPARQL 1.1 Overview SPARQL 1.1 Query Language SPARQL 1.1 Update SPARQL1.1 Service Description SPARQL 1.1 Federated Query SPARQL 1.1 Query Results JSON Format SPARQL 1.1 Query Results CSV and TSV Formats SPARQL Query Results XML Format (Second Edition) SPARQL 1.1 Entailment Regimes SPARQL 1.1 Protocol SPARQL 1.1 Graph Store HTTP Protocol No Substantive Changes There have been no substantive changes to this document since the previous version change log color-coded diff Please Send Comments Please send any comments to [email protected] public archive SPARQL Working Group errata [email protected] public archive Endorsed By W3C This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web. Patents This document was produced by a group operating under the 5 February 2004 W3C Patent Policy public list of any patent disclosures Essential Claim(s) section 6 of the W3C Patent Policy 1 Introduction Document Outline Document Conventions Namespaces Data Descriptions Result Descriptions Terminology Making Simple Queries (Informative) Writing a Simple Query Multiple Matches Matching RDF Literals Matching Literals with Language Tags Matching Literals with Numeric Types Matching Literals with Arbitrary Datatypes Blank Node Labels in Query Results Creating Values with Expressions Building RDF Graphs RDF Term Constraints (Informative) Restricting the Value of Strings Restricting Numeric Values Other Term Constraints SPARQL Syntax RDF Term Syntax Syntax for IRIs Prefixed Names Relative IRIs Syntax for Literals Syntax for Query Variables Syntax for Blank Nodes Syntax for Triple Patterns Predicate-Object Lists Object Lists RDF Collections rdf:type Graph Patterns Basic Graph Patterns Blank Node Labels Extending Basic Graph Pattern Matching Group Graph Patterns Empty Group Pattern Scope of Filters Group Graph Pattern Examples Including Optional Values Optional Pattern Matching Constraints in Optional Pattern Matching Multiple Optional Graph Patterns Matching Alternatives Negation Filtering Using Graph Patterns Testing For the Absence of a Pattern Testing For the Presence of a Pattern Removing Possible Solutions Relationship and differences between NOT EXISTS and MINUS Example: Sharing of variables Example: Fixed pattern Example: Inner FILTERs Property Paths Property Path Syntax Examples Property Paths and Equivalent Patterns Arbitrary Length Path Matching Assignment BIND: Assigning to Variables VALUES: Providing inline data VALUES syntax VALUES Examples Aggregates Aggregate Example GROUP BY HAVING Aggregate Projection Restrictions Aggregate Example (with errors) Subqueries RDF Dataset Examples of RDF Datasets Specifying RDF Datasets Specifying the Default Graph Specifying Named Graphs Combining FROM and FROM NAMED Querying the Dataset Accessing Graph Names Restricting by Graph IRI Restricting Possible Graph IRIs Named and Default Graphs Basic Federated Query Solution Sequences and Modifiers ORDER BY Projection Duplicate Solutions OFFSET LIMIT Query Forms SELECT Projection SELECT Expressions CONSTRUCT Templates with Blank Nodes Accessing Graphs in the RDF Dataset Solution Modifiers and CONSTRUCT CONSTRUCT WHERE ASK DESCRIBE (Informative) Explicit IRIs Identifying Resources Descriptions of Resources Expressions and Testing Values Operand Data Types Filter Evaluation Invocation Effective Boolean Value (EBV) Operator Mapping Operator Extensibility Function Definitions Functional Forms bound IF COALESCE NOT EXISTS and EXISTS logical-or logical-and RDFterm-equal sameTerm IN NOT IN Functions on RDF Terms isIRI isBlank isLiteral isNumeric str lang datatype IRI BNODE STRDT STRLANG UUID STRUUID Functions on Strings Strings in SPARQL Functions String arguments Argument Compatibility Rules String Literal Return Type STRLEN SUBSTR UCASE LCASE STRSTARTS STRENDS CONTAINS STRBEFORE STRAFTER ENCODE_FOR_URI CONCAT langMatches REGEX REPLACE Functions on Numerics abs round ceil floor RAND Functions on Dates and Times now year month day hours minutes seconds timezone tz Hash Functions MD5 SHA1 SHA256 SHA384 SHA512 XPath Constructor Functions Extensible Value Testing Definition of SPARQL Initial Definitions RDF Terms Simple Literal RDF Dataset Query Variables Triple Patterns Basic Graph Patterns Property Path Patterns Solution Mapping Solution Sequence Modifiers SPARQL Query Translation to the SPARQL Algebra Variable Scope Converting Graph Patterns Expand Syntax Forms Collect FILTER Elements Translate Property Path Expressions Translate Property Path Patterns Translate Basic Graph Patterns Translate Graph Patterns Filters of Group Simplification step Examples of Mapped Graph Patterns Converting Groups, Aggregates, HAVING, final VALUES clause and SELECT Expressions Grouping and Aggregation HAVING VALUES SELECT Expressions Converting Solution Modifiers ORDER BY Projection DISTINCT REDUCED OFFSET and LIMIT Final Algebra Expression Basic Graph Patterns SPARQL Basic Graph Pattern Matching Treatment of Blank Nodes Property Path Patterns SPARQL Algebra Aggregate Algebra Set Functions Count Sum Avg Min Max GroupConcat Sample Evaluation Semantics Extending SPARQL Basic Graph Matching Notes SPARQL Grammar SPARQL Request String Codepoint Escape Sequences White Space Comments IRI References Blank Nodes and Blank Node Labels Escape sequences in strings Grammar Conformance Security Considerations (Informative) Internet Media Type, File Extension and Macintosh File Type A References Normative References Other References RDF is a directed, labeled graph data format 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 Data Access Use Cases and Requirements UCNR SPARQL New Features and Rationale UCNR2 Unless otherwise noted in the section heading, all sections and appendices in this document are normative. This section of the document, section 1 Section 2 Section 3 Section 4 Section 5 Section 6 Section 7 Section 8 Section 9 Section 10 Sections 11 Section 12 Section 13 Section 14 SPARQL 1.1 Federated Query Section 15 Section 16 Section 17 Section 18 Section 19 SPARQL update In this document, examples assume the following namespace prefix bindings 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# sfn: http://www.w3.org/ns/sparql# This document uses the Turtle TURTLE @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 x y z x "Alice" y <http://example/a> z The SPARQL language includes IRIs, a subset of RDF URI References that omits spaces. Note that all IRIs in SPARQL queries are absolute; they may or may not include a fragment identifier [ RFC3987 RFC3986 relative IRIs and prefixed names The following terms are defined in RDF Concepts and Abstract Syntax [CONCEPTS] IRI RDF URI reference literal lexical form plain literal language tag typed literal datatype IRI datatype URI blank node In addition, we define the following terms: RDF Term Simple Literal Most forms of SPARQL query contain a set of triple patterns called a basic graph pattern matches RDF terms 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 WHERE ?title 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 Data: @prefix foaf: < http://xmlns.com/foaf/0.1/ 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:[email protected]> "Peter Goodguy" <mailto:[email protected]> 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:[email protected]> . _:b foaf:name "Peter Goodguy" . _:b foaf:box <mailto:[email protected]> . This is a basic graph pattern match 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#> . Note that, in Turtle, "cat"@en "42"^^xsd:integer http://www.w3.org/2001/XMLSchema#integer "abc"^^dt:specialDatatype 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 @ Best Common Practice 47 BCP47 This following query has no solution because "cat" "cat"@en SELECT ?v WHERE { ?v ?p "cat" } v but the query below will find a solution where variable v :x SELECT ?v WHERE { ?v ?p "cat"@en } v <http://example.org/ns#x> Integers in a SPARQL query indicate an RDF typed literal with the datatype xsd:integer 42 "42"^^<http://www.w3.org/2001/XMLSchema#integer> The pattern in the following query has a solution with variable v :y SELECT ?v WHERE { ?v ?p 42 } v <http://example.org/ns#y> Section 4.1.2 xsd:float xsd:double The following query has a solution with variable v :z 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 label. Blank node labels are scoped to a result set (see " SPARQL Query Results XML Format SPARQL 1.1 Query Results JSON Format CONSTRUCT 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 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 label _:a An application writer should not expect blank node labels in a query to refer to a particular blank node in the data. SPARQL 1.1 allows to create values from complex expressions. The queries below show how to the CONCAT expression in the SELECT BIND Data: @prefix foaf: <http://xmlns.com/foaf/0.1/> . _:a foaf:givenName "John" . _:a foaf:surname "Doe" . Query: PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ( CONCAT(?G, " ", ?S) AS ?name ) WHERE { ?P foaf:givenName ?G ; foaf:surname ?S } 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 SELECT CONSTRUCT 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 <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 FILTER TRUE This section provides an informal introduction to SPARQL FILTER Expressions and Testing Values comprehensive function library 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 . SPARQL FILTER regex regex string literals regex str 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 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 1.0 and XPath 2.0 Functions and Operators XML Schema Regular Expressions SPARQL FILTER 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 :book2 :book2 30.5 In addition to numeric xsd:string xsd:boolean xsd:dateTime Operand Data Types Operator Mapping Function Definitions This section covers the syntax used by SPARQL for RDF terms triple patterns section 19 The iri RFC3987 RFC3986 PrefixedName IRIREF irelative-ref RFC3987 The set of RDF terms defined in RDF Concepts and Abstract Syntax includes RDF URI references while SPARQL terms include IRIs. RDF URI references containing " < > " { } | \ ^ ` The PREFIX : SPARQL local names XML local names SPARQL local names ns:id\=123 SPARQL local names CURIE Relative IRIs are combined with base IRIs as per Uniform Resource Identifier (URI): Generic Syntax RFC3986 Internationalized Resource Identifiers (IRIs) RFC3987 The BASE 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, "..." '...' @ ^^ As a convenience, integers can be written directly (without quotation marks and an explicit datatype IRI) and are interpreted as typed literals of datatype xsd:integer xsd:decimal xsd:double xsd:boolean true 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 "xyz"^^<http://example.org/ns/userDatatype> "abc"^^appNS:appDataType '''The librarian said, "Perhaps you would enjoy 'War and Peace'."''' 1 "1"^^xsd:integer 1.3 "1.3"^^xsd:decimal 1.300 "1.300"^^xsd:decimal 1.0e6 "1.0e6"^^xsd:double true "true"^^xsd:boolean false "false"^^xsd:boolean Tokens matching the productions INTEGER DECIMAL DOUBLE BooleanLiteral xsd:integer xsd:decimal xsd:double 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 ?abc possible names SPARQL grammar Blank nodes Blank nodes are indicated by either the label form, such as " _:abc [] [] _:abc abc The [:p :v] The following two forms [ :p "v" ] . [] :p "v" . allocate a unique blank node label (here " b57 _: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" . 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 common predicates [ foaf:name ?name ; foaf:mbox <mailto:[email protected]> ] This is the same as writing the following basic graph pattern for some uniquely allocated blank node label, " b18 _:b18 foaf:name ?name . _:b18 foaf:mbox <mailto:[email protected]> . Triple Patterns 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 " ; ?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 () http://www.w3.org/1999/02/22-rdf-syntax-ns#nil (1 ?x 3 4) (1 ?x 3 4) :p "w" . is syntactic sugar for (noting that b0 b1 b2 b3 _: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 http://www.w3.org/1999/02/22-rdf-syntax-ns#type ?x a :Class1 . [ a :appClass ] :p "v" . is syntactic sugar for: ?x rdf:type :Class1 . _:b0 rdf:type :appClass . _:b0 :p "v" . SPARQL is based around graph pattern matching. More complex graph patterns can be formed by combining smaller patterns in various ways: Basic Graph Patterns Group Graph Pattern Optional Graph patterns Alternative Graph Pattern Patterns on Named Graphs 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 [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 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 SPARQL 1.1 Entailment Regimes In a SPARQL query string, a group graph pattern is delimited with braces: {} 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 into two basic graph patterns. For example, the query below has a different structure but would yield the same solutions as the previous query: 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 A constraint, expressed by the keyword FILTER { ?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 pattern The syntactic form: { OPTIONAL { pattern is equivalent to: { { } OPTIONAL { pattern The OPTIONAL pattern pattern is the same as: { pattern 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:[email protected]> . _:a foaf:mbox <mailto:[email protected]> .
_:b rdf:type foaf:Person . _:b foaf:name "Bob" . Query: 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:[email protected]> "Alice" <mailto:[email protected]> "Bob" There is no value of mbox "Bob" This query finds the names of people in the data. If there is a triple with predicate mbox 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. 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:[email protected]> . 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:[email protected]> 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 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" . _:a dc10:creator "Alice" .
_:b dc11:title "SPARQL Protocol Tutorial" . _:b dc11:creator "Bob" .
_: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 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 UNION y UNION The UNION 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 NOT EXISTS EXISTS apply to the whole group in which the filter appears The NOT EXISTS 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 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 Data: @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" . Query: 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 MINUS @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 } ?s ?p ?o NOT EXISTS { ?x ?y ?z } s p o whereas with MINUS ?s ?p ?o ?x ?y ?z 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: 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 FILTER NOT EXISTS @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 ?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 FILTER 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 can not 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 an IRI written in full or abbreviated by a prefixed name a elt 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 elt2 elt1 elt2 AlternativePath A alternative path of elt1 elt2 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 !( iri 1 iri n NegatedPropertySet Negated property set. An IRI which is not one of iri i ! iri ! (iri) !^ iri !(^ iri 1 iri n NegatedPropertySet Negated property set where the excluded matches are based on reversed path. iri 1 iri n !^ iri !(^ iri !( iri 1 iri j iri j+1 iri n NegatedPropertySet A combination of forward and reverse properties in a negated property set. ( elt A group path elt 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: IRI, prefixed names Negated property sets Groups Unary operators * ? + Unary ^ inverse links Binary operator / Binary operator | Precedence is left-to-right within groups. Alternatives { :book1 dc:title|rdfs:label ?displayString } which could have writen: { :book1 <http://purl.org/dc/elements/1.1/title> | <http://www.w3.org/2000/01/rdf-schema#label> ?displayString } Sequence { ?x foaf:mbox <mailto:alice@example> . ?x foaf:knows/foaf:name ?name . } Sequence foaf:knows { ?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 { ?x foaf:mbox <mailto:alice@example> . ?x foaf:knows/foaf:knows ?y . FILTER ( ?x != ?y ) ?y foaf:name ?name } Inverse Property Paths { ?x foaf:mbox <mailto:alice@example> } { <mailto:alice@example> ^foaf:mbox ?x } Inverse Path Sequence ?x { ?x foaf:knows/^foaf:knows ?y . FILTER(?x != ?y) } which is equivalent to ( ?gen1 { ?x foaf:knows ?gen1 . ?y foaf:knows ?gen1 . FILTER(?x != ?y) } Arbitrary length match 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 { <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 { ?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. Some property paths are equivalent to a translation 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 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 equivalance 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, * + ? 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 foaf:knows 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 expressions in the SELECT expressions in the GROUP BY ( expression 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 The BIND BIND BIND 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 FILTER 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 solution sequence join federated query SERVICE VALUES In the following example, there is a table of two variables, ?x ?y ?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") } A VALUES SELECT 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 UNDEF 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 SELECT 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 Aggregates defined in version 1.1 of SPARQL are COUNT SUM MIN MAX AVG GROUP_CONCAT 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 ?org HAVING FILTER The example is produced by grouping solutions according to the GROUP BY ?org SUM HAVING SUM(?lprice) In aggregate queries and sub-queries, variables that appear in the query pattern, but are not in the GROUP BY SAMPLE Projection Restrictions It should be noted that as per functions BIND AS ?totalPrice WHERE 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 ORDER BY GROUP BY Within GROUP BY AS GROUP BY (?x + ?y AS ?z) { ... 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 FILTER HAVING An example of the use of HAVING 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 aggregates, only expressions consisting of aggregates and constants may be projected, with one exception. When GROUP BY For example, the following query is legal as ?x is given as a GROUP BY 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) GROUP BY (STR(?z) AS ?strZ) ?strZ Other expressions, not using GROUP BY SAMPLE This section shows an example query using aggregation, which demonstrates how errors are handled in results, in the presence of aggregates. Data: @prefix : <http://example.com/data/#> .
:x :p 1, 2, 3, 4 . :y :p 1, _:b2, 3, 4 . :z :p 1.0, 2.0, 3.0, 4 . Query: PREFIX : <http://example.com/data/#> SELECT ?g (AVG(?p) AS ?avg) ((MIN(?p) + MAX(?p)) / 2 AS ?c) WHERE { ?g :p ?p . } GROUP BY ?g Result: g avg c <http://example.com/data/#x> 2.5 2.5 <http://example.com/data/#y> <http://example.com/data/#z> 2.5 2.5 Note that the bindings for the :y group is not included in the results as the evaluation of Avg({1, _:b2, 3, 4}), and (_:b2 + 4) / 2 is an error, removing the bindings from the solution. Subqueries are a way to embed SPARQL queries within other queries, normally to achieve results which cannot otherwise be achieved, such as limiting the number of results from some sub-expression within the query. Due to the bottom-up nature of SPARQL query evaluation, the subqueries are evaluated logically first, and the results are projected up to the outer query. Note that only variables projected out of the subquery will be visible, or in scope Example Data: @prefix : <http://people.example/> .
:alice :name "Alice", "Alice Foo", "A. Foo" . :alice :knows :bob, :carol . :bob :name "Bob", "Bob Bar", "B. Bar" . :carol :name "Carol", "Carol Baz", "C. Baz" . Return a name (the one with the lowest sort order) for all the people that know Alice and have a name. Query: PREFIX : <http://people.example/> PREFIX : <http://people.example/> SELECT ?y ?minName WHERE { :alice :knows ?y . { SELECT ?y (MIN(?name) AS ?minName) WHERE { ?y :name ?name . } GROUP BY ?y } } Results: y minName :bob "B. Bar" :carol "C. Baz" This result is achieved by first evaluating the inner query: SELECT ?y (MIN(?name) AS ?minName) WHERE { ?y :name ?name . } GROUP BY ?y This produces the following solution sequence: y minName :alice "A. Foo" :bob "B. Bar" :carol "C. Baz" Which is joined with the results of the outer query: y :bob :carol The RDF data model expresses information as graphs consisting 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 13.3 Querying the Dataset An RDF Dataset may contain zero named graphs; an RDF Dataset always contains one default graph. A query does not need to involve matching the default graph; the query can just involve matching named graphs. The graph that is used for matching a basic graph pattern is the active graph GRAPH The definition of RDF Dataset does not restrict the relationships of named and default graphs. Information can be repeated in different graphs; relationships between graphs can be exposed. Two useful arrangements are: to have information in the default graph that includes provenance information about the named graphs to include the information in the named graphs in the default graph as well. Example 1: # Default graph # Named graph: http://example.org/bob # Named graph: http://example.org/alice 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 the RDF merge RDF-MT 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 # Named graph: http://example.org/bob # Named graph: http://example.org/alice mailto:[email protected] In an RDF merge, blank nodes in the merged graph are not shared with blank nodes from the graphs being merged. A SPARQL query may specify the dataset to be used for matching by using the FROM FROM NAMED specified in a SPARQL protocol request The FROM FROM NAMED FROM FROM NAMED a default graph consisting of the RDF merge of the graphs referred to in the FROM a set of (IRI, graph) pairs, one from each FROM NAMED If there is no FROM FROM NAMED Each FROM In this example, the RDF Dataset contains a single default graph and no named graphs: # Default graph (located at http://example.org/foaf/aliceFoaf) 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 RDF merge A query can supply IRIs for the named graphs in the RDF Dataset using the FROM NAMED FROM NAMED # Graph: http://example.org/bob # Graph: http://example.org/alice ... FROM NAMED <http://example.org/alice> FROM NAMED <http://example.org/bob> ... The FROM NAMED further details WEBARCH The FROM FROM NAMED # Default graph (located at http://example.org/dft.ttl) # Named graph: http://example.org/bob # Named graph: http://example.org/alice 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 } } The RDF Dataset for this query contains a default graph and two named graphs. The GRAPH The actions required to construct the dataset are not determined by the dataset description alone. If an IRI is given twice in a dataset description, either by using two FROM FROM FROM NAMED When querying a collection of graphs, the GRAPH GRAPH The use of GRAPH GRAPH The following two graphs will be used in examples: # Named graph: http://example.org/foaf/aliceFoaf # Named graph: http://example.org/foaf/bobFoaf The query below matches the graph pattern against each of the named graphs in the dataset and forms solutions which have the src PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?src ?bobNick FROM NAMED <http://example.org/foaf/aliceFoaf> FROM NAMED <http://example.org/foaf/bobFoaf> WHERE { GRAPH ?src { ?x foaf:mbox <mailto:[email protected]> . ?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" The query can restrict the matching applied to a specific graph by supplying the graph IRI. This sets the active graph to the graph named by the 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 FROM NAMED <http://example.org/foaf/aliceFoaf> FROM NAMED <http://example.org/foaf/bobFoaf> WHERE { GRAPH data:bobFoaf { ?x foaf:mbox <mailto:[email protected]> . ?x foaf:nick ?nick } } which yields a single solution: nick "Robert" A variable used in the GRAPH GRAPH The query below uses the graph with IRI http://example.org/foaf/aliceFoaf GRAPH w mbox GRAPH whom whom 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 FROM NAMED <http://example.org/foaf/aliceFoaf> FROM NAMED <http://example.org/foaf/bobFoaf> WHERE { GRAPH data:aliceFoaf { ?alice foaf:mbox <mailto:[email protected]> ; 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:[email protected]> "Robert" <http://example.org/foaf/bobFoaf> Any triple in Alice's FOAF file giving Bob's nick nick ppd 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. In this example, 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 # Graph: locally allocated IRI: tag:example.org,2005-06-06:graph1 # Graph: locally allocated IRI: tag:example.org,2005-06-06:graph2 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:[email protected]> "2004-12-06"^^xsd:date "Bob" <mailto:[email protected]> "2005-01-10"^^xsd:date This document incorporates the syntax for SPARQL federation extensions. This feature is defined in the document SPARQL 1.1 Federated Query Query patterns generate an unordered collection of solutions, each solution SPARQL query form A solution sequence modifier Order Projection Distinct Reduced Offset Limit Modifiers are applied in the order given by the list above. The ORDER BY Following the ORDER BY ASC() DESC() ASC() DESC() 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/>
SELECT ?name WHERE { ?x foaf:name ?name ; :empId ?emp } ORDER BY DESC(?emp) PREFIX : <http://example.org/ns#> PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name WHERE { ?x foaf:name ?name ; :empId ?emp } ORDER BY ?name DESC(?emp) The "<" operator Operator Mapping 17.3.1 Operator Extensibility numerics simple literals xsd:strings xsd:booleans xsd:dateTimes simple literals SPARQL also fixes an order between some kinds of RDF terms that would not otherwise be ordered: (Lowest) no value assigned to the variable or expression in this solution. Blank nodes IRIs RDF literals A plain literal is lower than an RDF literal with type xsd:string SPARQL does not define a total ordering of all possible RDF terms. Here are a few examples of pairs of terms for which the relative order is undefined: "a" and "a"@en_gb (a simple literal and a literal with a language tag) "a"@en_gb and "b"@en_gb (two literals with language tags) "a" and "1"^^xsd:integer (a simple literal and a literal with a supported datatype) "1"^^my:integer and "2"^^my:integer (two unsupported datatypes) "1"^^xsd:integer and "2"^^my:integer (a supported datatype and an unsupported datatype) This list of variable bindings is in ascending order: RDF Term Reason Unbound results sort earliest. _:z Blank nodes follow unbound. _:a There is no relative ordering of blank nodes. <http://script.example/Latin> IRIs follow blank nodes. <http://script.example/Кириллица> The character in the 23rd position, "К", has a unicode codepoint 0x41A, which is higher than 0x4C ("L"). <http://script.example/漢字> The character in the 23rd position, "漢", has a unicode codepoint 0x6F22, which is higher than 0x41A ("К"). "http://script.example/Latin" Simple literals follow IRIs. "http://script.example/Latin"^^xsd:string xsd:strings follow simple literals. The ascending order of two solutions with respect to an ordering comparator is established by substituting the solution bindings into the expressions and comparing them with the "<" operator The relative order of two solutions is the relative order of the two solutions with respect to the first ordering comparator in the sequence. For solutions where the substitutions of the solution bindings produce the same RDF term, the order is the relative order of the two solutions with respect to the next ordering comparator. The relative order of two solutions is undefined if no order expression evaluated for the two solutions produces distinct RDF terms. Ordering a sequence of solutions always results in a sequence with the same number of solutions in it. Using ORDER BY CONSTRUCT DESCRIBE SELECT LIMIT OFFSET ORDER BY ASK ORDER BY LIMIT OFFSET 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 using the SELECT query form. 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:[email protected]> .
_:b foaf:name "Bob" . _:b foaf:mbox <mailto:[email protected]> . PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?name WHERE { ?x foaf:name ?name } name "Bob" "Alice" A solution sequence with no DISTINCT REDUCED Data: @prefix foaf: <http://xmlns.com/foaf/0.1/> .
_:x foaf:name "Alice" . _:x foaf:mbox <mailto:[email protected]> .
_:y foaf:name "Alice" . _:y foaf:mbox <mailto:[email protected]> .
_:z foaf:name "Alice" . _:z foaf:mbox <mailto:[email protected]> . Query: PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?name WHERE { ?x foaf:name ?name } Results: name "Alice" "Alice" "Alice" The modifiers DISTINCT REDUCED The DISTINCT PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT DISTINCT ?name WHERE { ?x foaf:name ?name } name "Alice" Note that, per the order of solution sequence modifiers While the DISTINCT REDUCED REDUCED DISTINCT REDUCED PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT REDUCED ?name WHERE { ?x foaf:name ?name } may have one, two (shown here) or three solutions: name "Alice" "Alice" OFFSET OFFSET Using LIMIT OFFSET ORDER BY PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name WHERE { ?x foaf:name ?name } ORDER BY ?name LIMIT 5 OFFSET 10 The LIMIT OFFSET PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name WHERE { ?x foaf:name ?name } LIMIT 20 A LIMIT SPARQL has four query forms. These query 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. ASK Returns a boolean indicating whether a query pattern matches or not. DESCRIBE Returns an RDF graph that describes the resources found. Formats such as SPARQL 1.1 Query Results JSON Format SPARQL Query Results XML Format SPARQL 1.1 Query Results CSV and TSV Formats SELECT ASK The SELECT form of results returns variables and their bindings directly. It combines the operations of projecting the required variables with introducing new variable bindings into a query solution. Specific variables and their bindings are returned when a list of variable names is given in the SELECT clause. The syntax SELECT * in-scope FILTER MINUS Use of SELECT * GROUP BY @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" Result sets can be accessed by a local API but also can be serialized into either JSON, XML, CSV or TSV. SPARQL 1.1 Query Results JSON Format { "head": { "vars": [ "nameX" , "nameY" , "nickY" ] } , "results": { "bindings": [ { "nameX": { "type": "literal" , "value": "Alice" } , "nameY": { "type": "literal" , "value": "Bob" } } , { "nameX": { "type": "literal" , "value": "Alice" } , "nameY": { "type": "literal" , "value": "Clare" } , "nickY": { "type": "literal" , "value": "CT" } } ] } } SPARQL Query Results XML Format <?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> </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> As well as choosing which variables from the pattern matching are included in the results, the SELECT clause can also introduce new variables. The rules of assignment in SELECT expression are the same as for assignment in BIND. The expression combines variable bindings already in the query solution, or defined earlier in the SELECT clause, to produce a binding in the query solution. The scoping for (expr AS v) SELECT SELECT SELECT 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 (?p*(1-?discount) AS ?price) { ?x ns:price ?p . ?x dc:title ?title . ?x ns:discount ?discount } Results: title price "The Semantic Web" 17.25 "SPARQL Tutorial" 33.6 New variables can also be used in expressions if they are introduced earlier, syntactically, in the same SELECT clause: PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX ns: <http://example.org/ns#> SELECT ?title (?p AS ?fullPrice) (?fullPrice*(1-?discount) AS ?customerPrice) { ?x ns:price ?p . ?x dc:title ?title . ?x ns:discount ?discount } Results: title fullPrice customerPrice "The Semantic Web" 23 17.25 "SPARQL Tutorial" 42 33.6 The CONSTRUCT 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 output RDF graph. The graph template can contain triples with no variables (known as ground or explicit triples), and these also appear in the output RDF graph returned by the CONSTRUCT query form. @prefix foaf: <http://xmlns.com/foaf/0.1/> .
_:a foaf:name "Alice" . _:a foaf:mbox <mailto:[email protected]> . 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" . 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 for 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 _:a _:b _:v1 _:v2 Using CONSTRUCT http://example.org/aGraph CONSTRUCT { ?s ?p ?o } WHERE { GRAPH <http://example.org/aGraph> { ?s ?p ?o } . } The access to the graph can be conditional on other information. For example, if 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#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
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 extension function xsd:dateTime The solution modifiers of a query affect the results of a CONSTRUCT CONSTRUCT @prefix foaf: <http://xmlns.com/foaf/0.1/> . @prefix site: <http://example.org/stats#> .
_:a foaf:name "Alice" . _:a site:hits 2349 .
_:b foaf:name "Bob" . _:b site:hits 105 .
_:c foaf:name "Eve" . _:c 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 desc(?hits) LIMIT 2 @prefix foaf: <http://xmlns.com/foaf/0.1/> . _:x foaf:name "Alice" . _:y foaf:name "Eve" . A short form for the CONSTRUCT query form is provided for the case where the template and the pattern are the same and the pattern is just a basic graph pattern (no FILTER WHERE The following two queries are the same; the first is a short form of the second. PREFIX foaf: <http://xmlns.com/foaf/0.1/> CONSTRUCT WHERE { ?x foaf:name ?name } PREFIX foaf: <http://xmlns.com/foaf/0.1/>
CONSTRUCT { ?x foaf:name ?name } WHERE { ?x foaf:name ?name } Applications can use the ASK @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:[email protected]> . PREFIX foaf: <http://xmlns.com/foaf/0.1/> ASK { ?x foaf:name "Alice" } true The SPARQL Query Results XML Format <?xml version="1.0"?> <sparql xmlns="http://www.w3.org/2005/sparql-results#"> <head></head> <boolean>true</boolean> </sparql> On the same data, the following returns no match because Alice's mbox PREFIX foaf: <http://xmlns.com/foaf/0.1/> ASK { ?x foaf:name "Alice" ; foaf:mbox <mailto:[email protected]> } false The DESCRIBE DESCRIBE DESCRIBE * The DESCRIBE DESCRIBE DESCRIBE DESCRIBE <http://example.org/> The resources to be described can also be taken from the bindings to a query variable in 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 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} The RDF returned is determined by the information publisher. It may be information the service deems relevant to the resources being described. It may include information about other resources: for example, 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#> foaf:mbox_sha1sum "bee135d3af1e418104bc42904596fe148e90f033" ; foaf:mbox_sha1sum rdf:type owl:InverseFunctionalProperty . which includes the blank node closure for the vcard CBD 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 WHERE SPARQL FILTERs constraint FILTERs false 17.2.2 Effective Boolean Value XQUERY 2.3.1, Kinds of Errors FILTER RDF literals may have a datatype IRI @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 object of the first dc:date xsd:dateTime SPARQL expressions are constructed according to the grammar and provide access to functions (named by IRI) and operator functions (invoked by keywords and symbols in the SPARQL grammar). SPARQL operators can be used to 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 ) } The SPARQL operators are listed in section 17.3 In addition, SPARQL provides the ability to invoke arbitrary functions, including a subset of the XPath casting functions, listed in section 17.5 ... FILTER ( xsd:dateTime(?date) < xsd:dateTime("2005-01-01T00:00:00Z") ) ... Typographical convention in this section: XPath operators are labeled with the prefix op: op: SPARQL functions and operators operate on RDF terms and SPARQL variables. A subset of these functions and operators are taken from the XQuery 1.0 and XPath 2.0 Functions and Operators FUNCOP typed value typed literals string value lexical form atomic datatype datatype IRI typed literals SPARQL has additional operators which operate on specific subsets of RDF terms. When referring to a type, the following terms denote a typed literal XML Schema XSDT datatype IRI xsd:integer xsd:decimal xsd:float xsd:double xsd:string xsd:boolean xsd:dateTime The following terms identify additional types used in SPARQL value tests: numeric typed literals xsd:integer xsd:decimal xsd:float xsd:double simple literal plain literal language tag RDF term IRI literal blank node variable The following types are derived from numeric numeric xsd:nonPositiveInteger xsd:negativeInteger xsd:long xsd:int xsd:short xsd:byte xsd:nonNegativeInteger xsd:unsignedLong xsd:unsignedInt xsd:unsignedShort xsd:unsignedByte xsd:positiveInteger SPARQL language extensions may treat additional types as being derived from XML schema datatypes. SPARQL provides a subset of the functions and operators defined by XQuery Operator Mapping 2.2.3 Expression Processing Unlike XPath/XQuery, SPARQL functions do not process node sequences. When interpreting the semantics of XPath functions, assume that each argument is a sequence of a single node. Functions invoked with an argument of the wrong type will produce a type error xsd:boolean EBV rules Apart from BOUND COALESCE NOT EXISTS EXISTS Any expression other than logical-or || logical-and && A logical-or A logical-and A logical-or logical-and either The logical-and and logical-or truth table for true ( T F E A B A || B A && B T T T T T F T F F T T F F F F F T E T E E T T E F E E F E F E F E E E E SPARQL defines a syntax for invoking functions on a list of arguments. Unless otherwise noted, these are invoked as follows: Argument expressions are evaluated, producing argument values. The order of argument evaluation is not defined. Numeric arguments are promoted as necessary to fit the expected types for that function or operator. The function or operator is invoked on the argument values. If any of these steps fails, the invocation generates an error. The effects of errors are defined in Filter Evaluation There are also " functional forms Effective boolean value is used to calculate the arguments to the logical functions logical-and logical-or fn:not FILTER The XQuery Effective Boolean Value fn:boolean fn:boolean The EBV of any literal whose type is xsd:boolean numeric If the argument is a typed literal datatype xsd:boolean If the argument is a plain literal typed literal datatype xsd:string If the argument is a numeric typed literal numeric All other arguments, including unbound arguments, produce a type error. An EBV of true typed literal xsd:boolean typed literal xsd:boolean The SPARQL grammar identifies a set of operators (for instance, && * isIRI XQuery 1.0 and XPath 2.0 Functions and Operators FUNCOP section 17.4 xsd:integer = xsd:signedInt = numeric RDF terms SPARQL follows XPath's scheme for numeric type promotions and subtype substitution for arguments to numeric operators. The XPath Operator Mapping numeric xsd:integer xsd:decimal xsd:float xsd:double numeric XML Path Language (XPath) 2.0 XPATH20 numeric type promotions subtype substitution fn:not(op:numeric-equal(A, B)) fn:not op:numeric-equal The collation for fn:compare defined by XPath http://www.w3.org/2005/xpath-functions/collation/codepoint RDF term SPARQL Unary Operators Operator Type(A) Function Result type XQuery Unary Operators ! xsd:boolean (EBV) fn:not xsd:boolean + numeric op:numeric-unary-plus numeric - numeric op:numeric-unary-minus numeric SPARQL Binary Operators Operator Type(A) Type(B) Function Result type Logical Connectives A || xsd:boolean (EBV) xsd:boolean (EBV) logical-or xsd:boolean A && xsd:boolean (EBV) xsd:boolean (EBV) logical-and xsd:boolean XPath Tests A = numeric numeric op:numeric-equal xsd:boolean A = simple literal simple literal op:numeric-equal fn:compare xsd:boolean A = xsd:string xsd:string op:numeric-equal fn:compare STR STR xsd:boolean A = xsd:boolean xsd:boolean op:boolean-equal xsd:boolean A = xsd:dateTime xsd:dateTime op:dateTime-equal xsd:boolean A != numeric numeric fn:not op:numeric-equal xsd:boolean A != simple literal simple literal fn:not op:numeric-equal fn:compare xsd:boolean A != xsd:string xsd:string fn:not op:numeric-equal fn:compare STR STR xsd:boolean A != xsd:boolean xsd:boolean fn:not op:boolean-equal xsd:boolean A != xsd:dateTime xsd:dateTime fn:not op:dateTime-equal xsd:boolean A < numeric numeric op:numeric-less-than xsd:boolean A < simple literal simple literal op:numeric-equal fn:compare xsd:boolean A < xsd:string xsd:string op:numeric-equal fn:compare STR STR xsd:boolean A < xsd:boolean xsd:boolean op:boolean-less-than xsd:boolean A < xsd:dateTime xsd:dateTime op:dateTime-less-than xsd:boolean A > numeric numeric op:numeric-greater-than xsd:boolean A > simple literal simple literal op:numeric-equal fn:compare xsd:boolean A > xsd:string xsd:string op:numeric-equal fn:compare STR STR xsd:boolean A > xsd:boolean xsd:boolean op:boolean-greater-than xsd:boolean A > xsd:dateTime xsd:dateTime op:dateTime-greater-than xsd:boolean A <= numeric numeric logical-or op:numeric-less-than op:numeric-equal xsd:boolean A <= simple literal simple literal fn:not op:numeric-equal fn:compare xsd:boolean A <= xsd:string xsd:string fn:not op:numeric-equal fn:compare STR STR xsd:boolean A <= xsd:boolean xsd:boolean fn:not op:boolean-greater-than xsd:boolean A <= xsd:dateTime xsd:dateTime fn:not op:dateTime-greater-than xsd:boolean A >= numeric numeric logical-or op:numeric-greater-than op:numeric-equal xsd:boolean A >= simple literal simple literal fn:not op:numeric-equal fn:compare xsd:boolean A >= xsd:string xsd:string fn:not op:numeric-equal fn:compare STR STR xsd:boolean A >= xsd:boolean xsd:boolean fn:not op:boolean-less-than xsd:boolean A >= xsd:dateTime xsd:dateTime fn:not op:dateTime-less-than xsd:boolean XPath Arithmetic A * numeric numeric op:numeric-multiply numeric A / numeric numeric op:numeric-divide numeric A + numeric numeric op:numeric-add numeric A - numeric numeric op:numeric-subtract numeric SPARQL Tests A = RDF term RDF term RDFterm-equal xsd:boolean A != RDF term RDF term fn:not RDFterm-equal xsd:boolean effective boolean value of that argument. SPARQL language extensions may provide additional associations between operators and operator functions; this amounts to adding rows to the table above. No additional operator may yield a result that replaces any result other than a type error in the semantics defined above. The consequence of this rule is that SPARQL FILTER at least FILTER Additional mappings of the '<' operator are expected to control the relative ordering of the operands, specifically, when used in an ORDER BY This section defines the operators and functions introduced by the SPARQL Query language. The examples show the behavior of the operators as invoked by the appropriate grammatical constructs. xsd:boolean BOUND variable var Returns true var 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 . 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 ?givenName . OPTIONAL { ?x dc:date ?date } . FILTER ( bound(?date) ) } Query result: givenName "Bob" One may test that a graph pattern is not OPTIONAL graph pattern not bound Negation as Failure This query matches the people with a name no 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 Bob's dc:date "Bob" rdfTerm IF expression1 expression2 expression3 The IF effective boolean value expression2 expression3 expression2 expression3 IF Examples: Suppose ?x = 2, ?z = 0 and ?y is not bound in some query solution: IF(?x = 2, "yes", "no") returns "yes" IF(bound(?y), "yes", "no") returns "no" IF(?x=2, "yes", 1/?z) returns "yes", the expression 1/?z IF(?x=1, "yes", 1/?z) raises an error IF("2" > 1, "yes", "no") raises an error rdfTerm COALESCE expression, .... The COALESCE If none of the arguments evaluates to an RDF term, an error is raised. If no expressions are evaluated without error, an error is raised. Examples: Suppose ?x = 2 and ?y is not bound in some query solution: COALESCE(?x, 1/0) returns 2, the value of x COALESCE(1/0, ?x) returns 2 COALESCE(5, ?x) returns 5 COALESCE(?y, 3) returns 3 COALESCE(?y) raises an error because y There is a filter operator EXISTS EXISTS true false active graph NOT EXISTS fn:not(EXISTS{...}) xsd:boolean NOT EXISTS pattern Returns false pattern NOT EXISTS { pattern } fn:not(EXISTS { pattern }) xsd:boolean EXISTS pattern Returns true pattern Variables in the pattern solution mapping pattern To facilitate this, we introduce a function Exists xsd:boolean xsd:boolean left || xsd:boolean right Returns a logical OR left right logical-or effective boolean value Note: see section 17.2, Filter Evaluation || xsd:boolean xsd:boolean left && xsd:boolean right Returns a logical AND left right logical-and effective boolean value Note: see section 17.2, Filter Evaluation && xsd:boolean RDF term term1 = RDF term term2 Returns TRUE if term1 term2 Resource Description Framework (RDF): Concepts and Abstract Syntax CONCEPTS * term1 term2 term1 term2 IRIs 6.4 RDF URI References CONCEPTS term1 term2 literals 6.5.1 Literal Equality CONCEPTS term1 term2 blank node 6.6 Blank Nodes CONCEPTS @prefix foaf: <http://xmlns.com/foaf/0.1/> .
_:a foaf:name "Alice". _:a foaf:mbox <mailto:[email protected]> .
_:b foaf:name "Ms A.". _:b foaf:mbox <mailto:[email protected]> . This query finds the people who have multiple foaf:name 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 at a specific date and time (New Year's Day 2005, measures in timezone +00:00), 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("2005-01-01T00:00:00Z") ) } annotates <http://www.w3.org/TR/rdf-sparql-query/> * "iiii"^^my:romanNumeral = "iv"^^my:romanNumeral "iiii"^^my:romanNumeral != "iv"^^my:romanNumeral xsd:boolean sameTerm RDF term term1 RDF term term2 Returns TRUE if term1 term2 Resource Description Framework (RDF): Concepts and Abstract Syntax CONCEPTS @prefix foaf: <http://xmlns.com/foaf/0.1/> .
_:a foaf:name "Alice". _:a foaf:mbox <mailto:[email protected]> .
_:b foaf:name "Ms A.". _:b foaf:mbox <mailto:[email protected]> . This query finds the people who have multiple foaf:name 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 (sameTerm(?mbox1, ?mbox2) && !sameTerm(?name1, ?name2)) } Query result: name1 name2 "Alice" "Ms A." "Ms A." "Alice" Unlike RDFterm-equal sameTerm typed literals @prefix : <http://example.org/WMterms#> . @prefix t: <http://example.org/types#> .
_:c1 :label "Container 1" . _:c1 :weight "100"^^t:kilos . _:c1 :displacement "100"^^t:liters .
_:c2 :label "Container 2" . _:c2 :weight "100"^^t:kilos . _:c2 :displacement "85"^^t:liters .
_:c3 :label "Container 3" . _:c3 :weight "85"^^t:kilos . _:c3 :displacement "85"^^t:liters . PREFIX : <http://example.org/WMterms#> PREFIX t: <http://example.org/types#>
SELECT ?aLabel1 ?bLabel WHERE { ?a :label ?aLabel . ?a :weight ?aWeight . ?a :displacement ?aDisp .
?b :label ?bLabel . ?b :weight ?bWeight . ?b :displacement ?bDisp .
FILTER ( sameTerm(?aWeight, ?bWeight) && !sameTerm(?aDisp, ?bDisp)) } aLabel bLabel "Container 1" "Container 2" "Container 2" "Container 1" The test for boxes with the same weight may also be done with the '=' operator ( RDFterm-equal "100"^^t:kilos = "85"^^t:kilos boolean rdfTerm IN expression ... The IN operator mapping A list of zero terms on the right-hand side is legal. Errors in comparisons cause the IN The IN (lhs = expression1) || (lhs = expression2) || ... Examples: 2 IN (1, 2, 3) true 2 IN () false 2 IN (<http://example/iri>, "str", 2.0) true 2 IN (1/0, 2) true 2 IN (2, 1/0) true 2 IN (3, 1/0) raises an error boolean rdfTerm NOT IN expression ... The NOT IN operator mapping A list of zero terms on the right-hand side is legal. Errors in comparisons cause the NOT IN The NOT IN (lhs != expression1) && (lhs != expression2) && ... NOT IN (...) !(IN (...)) Examples: 2 NOT IN (1, 2, 3) false 2 NOT IN () true 2 NOT IN (<http://example/iri>, "str", 2.0) false 2 NOT IN (1/0, 2) false 2 NOT IN (2, 1/0) false 2 NOT IN (3, 1/0) raises an error xsd:boolean isIRI RDF term term xsd:boolean isURI RDF term term Returns true term IRI false isURI isIRI @prefix foaf: <http://xmlns.com/foaf/0.1/> .
_:a foaf:name "Alice". _:a foaf:mbox <mailto:[email protected]> .
_:b foaf:name "Bob" . _:b foaf:mbox "[email protected]" . This query matches the people with a name mbox 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:[email protected]> xsd:boolean isBlank RDF term term Returns true term blank node false @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 dc:creator 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 dc:creator _:c xsd:boolean isLiteral RDF term term Returns true term literal false @prefix foaf: <http://xmlns.com/foaf/0.1/> . _:a foaf:name "Alice". _:a foaf:mbox <mailto:[email protected]> .
_:b foaf:name "Bob" . _:b foaf:mbox "[email protected]" . This query is similar to the one in 17.4.2.1 name mbox foaf:mbox 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" "[email protected]" xsd:boolean isNumeric RDF term term Returns true term false term Operand Data Types Examples: isNumeric(12) true isNumeric("12") false isNumeric("12"^^xsd:nonNegativeInteger) true isNumeric("1200"^^xsd:byte) false isNumeric(<http://example/>) false simple literal STR literal ltrl simple literal STR IRI rsrc Returns the lexical form ltrl literal rsrc IRI @prefix foaf: <http://xmlns.com/foaf/0.1/> .
_:a foaf:name "Alice". _:a foaf:mbox <mailto:[email protected]> .
_:b foaf:name "Bob" . _:b foaf:mbox <mailto:[email protected]> . This query selects the set of people who use their work.example 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" <mailto:[email protected]> simple literal LANG literal ltrl Returns the language tag ltrl "" ltrl language tag language tag @prefix foaf: <http://xmlns.com/foaf/0.1/> .
_:a foaf:name "Robert"@en. _:a foaf:name "Roberto"@es. _:a foaf:mbox <mailto:[email protected]> . This query finds the Spanish foaf:name 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:[email protected]> iri DATATYPE literal literal Returns the datatype IRI literal If the literal is a typed literal, return the datatype IRI. If the literal is a simple literal, return xsd:string If the literal is literal with a language tag, return rdf:langString @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 the foaf:name 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 ?shoeSize WHERE { ?x foaf:name ?name ; eg:shoeSize ?shoeSize . FILTER ( datatype(?shoeSize) = xsd:integer ) } Query result: name shoeSize "Bob" 42 In SPARQL 1.0 DATATYPE DATATYPE Operator extensibility DATATYPE rdf:langString The SPARQL Working Group is using rdf:langString rdf:langString iri IRI simple literal iri IRI xsd:string iri IRI iri iri URI simple literal iri URI xsd:string iri URI iri The IRI RFC 3986 RFC 3987 The URI IRI If the function is passed an IRI, it returns the IRI unchanged. Passing any RDF term other than a simple literal, xsd:string or an IRI is an error. An implementation MAY Examples: IRI("http://example/") <http://example/> IRI(<http://example/>) <http://example/> blank node BNODE blank node BNODE simple literal blank node BNODE xsd:string The BNODE solution mapping This functionality is compatible with the treatment of blank nodes in SPARQL CONSTRUCT templates literal STRDT simple literal IRI The STRDT STRDT("123", xsd:integer) "123"^^<http://www.w3.org/2001/XMLSchema#integer> STRDT("iiii", <http://example/romanNumeral>) "iiii"^^<http://example/romanNumeral> literal STRLANG simple literal simple literal The STRLANG STRLANG("chat", "en") "chat"@en iri UUID Return a fresh IRI from the UUID URN scheme UUID() UUID() <urn:uuid:b9302fb5-642e-4d3b-af19-29a8f6d894c9> simple literal STRUUID Return a string that is the scheme specific part of UUID. That is, as a simple literal, the result of generating a UUID, converting to a simple literal and removing the initial urn:uuid: STRUUID() "73cd4307-8a99-4691-a608-b5bda64fb6c1" Certain functions (e.g. REGEX STRLEN CONTAINS string literal The term string literal The functions STRSTARTS STRENDS CONTAINS STRBEFORE STRAFTER Compatibility of two arguments is defined as: The arguments are simple literals or literals typed as xsd:string The arguments are plain literals with identical language tags The first argument is a plain literal with language tag and the second argument is a simple literal or literal typed as xsd:string Argument1 Argument2 Compatible? "abc" "b" yes "abc" "b"^^xsd:string yes "abc"^^xsd:string "b" yes "abc"^^xsd:string "b"^^xsd:string yes "abc"@en "b" yes "abc"@en "b"^^xsd:string yes "abc"@en "b"@en yes "abc"@fr "b"@ja no "abc" "b"@ja no "abc" "b"@en no "abc"^^xsd:string "b"@en no Functions that return a string literal do so with the string literal of the same kind as the first argument (simple literal, plain literal with same language tag, xsd:string). This includes SUBSTR STRBEFORE STRAFTER The function CONCAT xsd:integer STRLEN string literal The strlen fn:string-length xsd:integer strlen("chat") 4 strlen("chat"@en) 4 strlen("chat"^^xsd:string) 4 string literal SUBSTR string literal xsd:integer string literal SUBSTR string literal xsd:integer xsd:integer The substr fn:substring xsd:string source The arguments startingLoc length The index of the first character in a strings is 1. substr("foobar", 4) "bar" substr("foobar"@en, 4) "bar"@en substr("foobar"^^xsd:string, 4) "bar"^^xsd:string substr("foobar", 4, 1) "b" substr("foobar"@en, 4, 1) "b"@en substr("foobar"^^xsd:string, 4, 1) "b"^^xsd:string string literal UCASE string literal The UCASE fn:upper-case ucase("foo") "FOO" ucase("foo"@en) "FOO"@en ucase("foo"^^xsd:string) "FOO"^^xsd:string string literal LCASE string literal The LCASE fn:lower-case lcase("BAR") "bar" lcase("BAR"@en) "bar"@en lcase("BAR"^^xsd:string) "bar"^^xsd:string xsd:boolean STRSTARTS string literal string literal The STRSTARTS fn:starts-with argument compatible For such input pairs, the function returns true if the lexical form of arg1 arg2 strStarts("foobar", "foo") true strStarts("foobar"@en, "foo"@en) true strStarts("foobar"^^xsd:string, "foo"^^xsd:string) true strStarts("foobar"^^xsd:string, "foo") true strStarts("foobar", "foo"^^xsd:string) true strStarts("foobar"@en, "foo") true strStarts("foobar"@en, "foo"^^xsd:string) true xsd:boolean STRENDS string literal string literal The STRENDS fn:ends-with argument compatible For such input pairs, the function returns true if the lexical form of arg1 arg2 strEnds("foobar", "bar") true strEnds("foobar"@en, "bar"@en) true strEnds("foobar"^^xsd:string, "bar"^^xsd:string) true strEnds("foobar"^^xsd:string, "bar") true strEnds("foobar", "bar"^^xsd:string) true strEnds("foobar"@en, "bar") true strEnds("foobar"@en, "bar"^^xsd:string) true xsd:boolean CONTAINS string literal string literal The CONTAINS fn:contains argument compatible contains("foobar", "bar") true contains("foobar"@en, "foo"@en) true contains("foobar"^^xsd:string, "bar"^^xsd:string) true contains("foobar"^^xsd:string, "foo") true contains("foobar", "bar"^^xsd:string) true contains("foobar"@en, "foo") true contains("foobar"@en, "bar"^^xsd:string) true literal STRBEFORE string literal string literal The STRBEFORE fn:substring-before argument compatible For compatible arguments, if the lexical part of the second argument occurs as a substring of the lexical part of the first argument, the function returns a literal of the same kind as the first argument arg1 arg1 arg2 arg2 If there is no such occurrence, an empty simple literal is returned. strbefore("abc","b") "a" strbefore("abc"@en,"bc") "a"@en strbefore("abc"@en,"b"@cy) error strbefore("abc"^^xsd:string,"") ""^^xsd:string strbefore("abc","xyz") "" strbefore("abc"@en, "z"@en) "" strbefore("abc"@en, "z") "" strbefore("abc"@en, ""@en) ""@en strbefore("abc"@en, "") ""@en literal STRAFTER string literal string literal The STRAFTER fn:substring-after argument compatible For compatible arguments, if the lexical part of the second argument occurs as a substring of the lexical part of the first argument, the function returns a literal of the same kind as the first argument arg1 arg1 arg2 arg2 arg1 If there is no such occurrence, an empty simple literal is returned. strafter("abc","b") "c" strafter("abc"@en,"ab") "c"@en strafter("abc"@en,"b"@cy) error strafter("abc"^^xsd:string,"") "abc"^^xsd:string strafter("abc","xyz") "" strafter("abc"@en, "z"@en) "" strafter("abc"@en, "z") "" strafter("abc"@en, ""@en) "abc"@en strafter("abc"@en, "") "abc"@en simple literal ENCODE_FOR_URI string literal The ENCODE_FOR_URI fn:encode-for-uri fn:encode-for-uri encode_for_uri("Los Angeles") "Los%20Angeles" encode_for_uri("Los Angeles"@en) "Los%20Angeles" encode_for_uri("Los Angeles"^^xsd:string) "Los%20Angeles" string literal CONCAT string literal ltrl 1 string literal ltrl n The CONCAT fn:concat The lexical form of the returned literal is obtained by concatenating the lexical forms of its inputs. If all input literals are typed literals of type xsd:string xsd:string concat("foo", "bar") "foobar" concat("foo"@en, "bar"@en) "foobar"@en concat("foo"^^xsd:string, "bar"^^xsd:string) "foobar"^^xsd:string concat("foo", "bar"^^xsd:string) "foobar" concat("foo"@en, "bar") "foobar" concat("foo"@en, "bar"^^xsd:string) "foobar" xsd:boolean langMatches simple literal language-tag simple literal language-range Returns true language-tag language-range RFC4647 language-range Matching of Language Tags RFC4647 language-range language-tag @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 . _:b dc:title "Il Buono, il Bruto, il Cattivo" . This query uses langMatches lang 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 ), "*" ) lang( ?v ) PREFIX dc: <http://purl.org/dc/elements/1.1/> SELECT ?title WHERE { ?x dc:title ?title . FILTER langMatches( lang(?title), "*" ) } will report all of the titles with a language tag: title "That Seventies Show"@en "Cette Série des Années Soixante-dix"@fr "Cette Série des Années Septante"@fr-BE xsd:boolean REGEX string literal text simple literal pattern xsd:boolean REGEX string literal text simple literal pattern simple literal flags Invokes the XPath fn:matches text pattern 7.6.1 Regular Expression Syntax FUNCOP @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" string literal REPLACE string literal simple literal simple literal string literal REPLACE string literal simple literal simple literal simple literal The REPLACE fn:replace pattern REGEX replace("abcd", "b", "Z") "aZcd" replace("abab", "B", "Z","i") "aZaZ" replace("abab", "B.", "Z","i") "aZb" numeric ABS numeric term Returns the absolute value of arg arg This function is the same as fn:numeric-abs XDM abs(1) 1 abs(-1.5) 1.5 numeric ROUND numeric term Returns the number with no fractional part that is closest to the argument. If there are two such numbers, then the one that is closest to positive infinity is returned. An error is raised if arg This function is the same as fn:numeric-round XDM round(2.4999) 2.0 round(2.5) 3.0 round(-2.5) -2.0 numeric CEIL numeric term Returns the smallest (closest to negative infinity) number with no fractional part that is not less than the value of arg arg This function is the same as fn:numeric-ceil XDM ceil(10.5) 11.0 ceil(-10.5) -10.0 numeric FLOOR numeric term Returns the largest (closest to positive infinity) number with no fractional part that is not greater than the value of arg arg This function is the same as fn:numeric-floor XDM floor(10.5) 10.0 floor(-10.5) -11.0 xsd:double RAND Returns a pseudo-random number between 0 (inclusive) and 1.0e0 (exclusive). Different numbers can be produced every time this function is invoked. Numbers should be produced with approximately equal probability. rand() "0.31221030831984886"^^xsd:double xsd:dateTime NOW Returns an XSD dateTime value for the current query execution. All calls to this function in any one query execution must return the same value. The exact moment returned is not specified. now() "2011-01-10T14:45:13.815-05:00"^^xsd:dateTime xsd:integer YEAR xsd:dateTime arg Returns the year part of arg This function corresponds to fn:year-from-dateTime year("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) 2011 xsd:integer MONTH xsd:dateTime arg Returns the month part of arg This function corresponds to fn:month-from-dateTime month("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) 1 xsd:integer DAY xsd:dateTime arg Returns the day part of arg This function corresponds to fn:day-from-dateTime day("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) 10 xsd:integer HOURS xsd:dateTime arg Returns the hours part of arg This function corresponds to fn:hours-from-dateTime hours("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) 14 xsd:integer MINUTES xsd:dateTime arg Returns the minutes part of the lexical form of arg This function corresponds to fn:minutes-from-dateTime minutes("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) 45 xsd:decimal SECONDS xsd:dateTime arg Returns the seconds part of the lexical form of arg This function corresponds to fn:seconds-from-dateTime seconds("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) 13.815 xsd:dayTimeDuration TIMEZONE xsd:dateTime arg Returns the timezone part of arg This function corresponds to fn:timezone-from-dateTime timezone("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) "-PT5H"^^xsd:dayTimeDuration timezone("2011-01-10T14:45:13.815Z"^^xsd:dateTime) "PT0S"^^xsd:dayTimeDuration timezone("2011-01-10T14:45:13.815"^^xsd:dateTime) error simple literal TZ xsd:dateTime arg Returns the timezone part of arg tz("2011-01-10T14:45:13.815-05:00"^^xsd:dateTime) "-05:00" tz("2011-01-10T14:45:13.815Z"^^xsd:dateTime) "Z" tz("2011-01-10T14:45:13.815"^^xsd:dateTime) "" simple literal MD5 simple literal arg simple literal MD5 xsd:string arg Returns the MD5 checksum, as a hex digit string, calculated on the UTF-8 representation of the simple literal or lexical form of the xsd:string SHOULD MD5("abc") "900150983cd24fb0d6963f7d28e17f72" MD5("abc"^^xsd:string) "900150983cd24fb0d6963f7d28e17f72" simple literal SHA1 simple literal arg simple literal SHA1 xsd:string arg Returns the SHA1 checksum, as a hex digit string, calculated on the UTF-8 representation of the simple literal or lexical form of the xsd:string SHOULD SHA1("abc") "a9993e364706816aba3e25717850c26c9cd0d89d" SHA1("abc"^^xsd:string) "a9993e364706816aba3e25717850c26c9cd0d89d" simple literal SHA256 simple literal arg simple literal SHA256 xsd:string arg Returns the SHA256 checksum, as a hex digit string, calculated on the UTF-8 representation of the simple literal or lexical form of the xsd:string SHOULD SHA256("abc") "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" SHA256("abc"^^xsd:string) "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" simple literal SHA384 simple literal arg simple literal SHA384 xsd:string arg Returns the SHA384 checksum, as a hex digit string, calculated on the UTF-8 representation of the simple literal or lexical form of the xsd:string SHOULD SHA384("abc") "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7" SHA384("abc"^^xsd:string) "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7" simple literal SHA512 simple literal arg simple literal SHA512 xsd:string arg Returns the SHA512 checksum, as a hex digit string, calculated on the UTF-8 representation of the simple literal or lexical form of the xsd:string SHOULD SHA512("abc") "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f" SHA512("abc"^^xsd:string) "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f" SPARQL imports a subset of the XPath constructor functions defined in XQuery 1.0 and XPath 2.0 Functions and Operators FUNCOP 17.1 Casting from primitive types to primitive types SPARQL operand datatypes additional datatypes XPath defines only the casts from one XML Schema datatype to another. The remaining casts are defined as follows: Casting an IRI xsd:string typed literal xsd:string Casting a simple literal xsd:string string value The table below summarizes the casting operations that are always allowed ( Y N M xsd:string xsd:float M bool = xsd:boolean xsd:double xsd:float xsd:decimal xsd:integer xsd:dateTime xsd:string IRI IRI ltrl simple literal From \ To str flt dbl dec int dT bool str Y M M M M M M flt Y Y Y M M N Y dbl Y Y Y M M N Y dec Y Y Y Y Y N Y int Y Y Y Y Y N Y dT Y N N N N Y N bool Y Y Y Y Y N Y IRI Y N N N N N N ltrl Y M M M M M M It should be noted that any function or operator that is specified to return an error under some conditions is a valid extension point. That is, an implementation may return a non-error value in these error cases, and still be conformant with this recommendation. A PrimaryExpression SPARQL queries using extension functions are likely to have limited interoperability. As an example, consider a function called func:even xsd:boolean func:even numeric value This function would be invoked in a FILTER as such: 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)) } For a second example, consider a function aGeo:distance xsd:double aGeo:distance numeric x1 numeric y1 numeric x2 numeric y2 PREFIX aGeo: <http://example.org/geo#>
SELECT ?neighbor WHERE { ?a aGeo:placeName "Grenoble" . ?a aGeo:locationX ?axLoc . ?a aGeo:locationY ?ayLoc .
?b aGeo:placeName ?neighbor . ?b aGeo:locationX ?bxLoc . ?b aGeo:locationY ?byLoc .
FILTER ( aGeo:distance(?axLoc, ?ayLoc, ?bxLoc, ?byLoc) < 10 ) . } An extension function 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. This section defines the correct behavior for evaluation of graph patterns and solution modifiers, given a query string and an RDF dataset. It does not imply a SPARQL implementation must use the process defined here. The outcome of executing a SPARQL query is defined by a series of steps, starting from the SPARQL query as a string, turning that string into an abstract syntax form, then turning the abstract syntax into a SPARQL abstract query comprising operators from the SPARQL algebra. This abstract query is then evaluated on an RDF dataset. SPARQL is defined in terms of IRIs [ RFC3987 Definition: RDF Term Let I be the set of all IRIs. RDF Literals blank nodes The set of RDF Terms This definition of RDF Term RDF data model updated Definition: Simple Literal The set of Simple Literals RDF Literals Definition: RDF Dataset An RDF dataset is a set: 1 1 2 2 n n i i i G is called the default graph. (<u i i Definition: Active Graph The active graph Definition: RDF Dataset Merge Let DS1 = { G1, (<u1 1 1 2 2 n n 1 1 2 2 m m then we define the RDF Dataset Merge of DS1 and DS2 to be: 1 1 2 2 k k Write N1 for { <u1 j j G is the merge (<u i i i (<u i i i (<u i i i j k i merge j k Definition: Query Variable A query variable Definition: Triple Pattern A triple pattern 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." Because RDF graphs may not contain literal subjects, any SPARQL triple pattern with a literal as subject will fail to match on any RDF graph. Definition: Basic Graph Pattern A Basic Graph Pattern Triple Patterns The empty graph pattern is a basic graph pattern which is the empty set. Definition: Property Path A Property Path is a sequence of triples, t i i i+1 We call the subject of t 0 We call the object of t n A Property Path is a path in graph G if each t i A property path does not span multiple graphs in a dataset. Definition: Property Path Expression A property path expression is an expression using the property path forms described above Definition: Property Path Pattern Let PP be the set of all property path expressions. A property path pattern is a member of the set: A Property Path Pattern is a generalization of a Triple Pattern A solution mapping is a mapping from a set of variables to a set of RDF terms. We use the term 'solution' where it is clear. Definition: Solution Mapping A solution mapping The domain of μ, dom(μ), is the subset of V where μ is defined. Definition: Solution Sequence A solution sequence Write expr(μ) for the value of the expression expr, using the terms for variables given by μ. Evaluation may result in an error. Definition: Solution Sequence Modifier A solution sequence modifier Order By Projection Distinct Reduced Offset Limit Definition: SPARQL Query A SPARQL Abstract Query E is a SPARQL algebra DS is an RDF Dataset QF is a query form Definition: Query Level A query level is a graph pattern, a set of group and aggregation, and a set of solution modifiers. A query is a tree of "query levels", where each subquery This section defines the process of converting graph patterns and solution modifiers in a SPARQL query string into a SPARQL algebra expression. The process described converts one level of query nesting, as formed by subqueries using the nested SELECT The SPARQL query string is parsed and the abbreviations for IRIs and triple patterns given in section 4 Patterns Modifiers Query Forms Other RDF terms DISTINCT SELECT VALUES Property path expression REDUCED CONSTRUCT SERVICE Property path patterns Projection DESCRIBE Groups ORDER BY ASK OPTIONAL LIMIT UNION OFFSET GRAPH Select expressions BIND GROUP BY HAVING MINUS FILTER The result of converting such an abstract syntax tree is a SPARQL query that uses the following symbols in the SPARQL algebra: Graph Pattern Solution Modifiers Property Path BGP ToList PredicatePath Join OrderBy InversePath LeftJoin Project SequencePath Filter Distinct AlernativePath Union Reduced ZeroOrMorePath Graph Slice OneOrMorePath Extend ToMultiSet ZeroOrOnePath Minus NegatedPropertySet Group Aggregation AggregateJoin Slice ToList ToMultiSet We define a variable to be in-scope Note that a subquery with a projection can hide variables; use of a variable in FILTER MINUS Let P P1 P2 E E1 En v Syntax Form In-scope variables Basic Graph Pattern (BGP) v Path v Group { P1 P2 ... } v GRAPH term { P } v term v { P1 } UNION { P2 } v OPTIONAL {P} v SERVICE term {P} v term v BIND (expr AS v) v SELECT .. v .. { P } v SELECT ... (expr AS v) v GROUP BY (expr AS v) v SELECT * { P } v P VALUES v { values } v VALUES varlist { values } v v varlist The variable v (expr AS v) (expr AS v) SELECT In BIND (expr AS v) v In SELECT v SELECT This section describes the process for translating a SPARQL graph pattern into a SPARQL algebra expression. This process is applied to the group graph pattern (the unit between {...} WHERE In summary, the steps are applied as follows: Expand syntax forms Translate property path expressions Convert some property path patterns to triples Collect the FILTER Translate Basic Graph Patterns Translate the remaining graph patterns in the group Add in Filters Simplify the algebra expression We write translate(graph pattern) for the algorthm described here to translate graph patterns. The working group notes that in SPARQL 1.0, the point at which the simplification step is applied leads to ambiguous transformation of queries involving a doubly nested filter and pattern in an optional: OPTIONAL { { ... FILTER ( ... ?x ... ) } }. This is illustrated by two non-normative test cases: Simplification applied after all transformations Simplification applied during transformation Applying the simpification step after all the translation of graph patterns is the preferred reading. Expand abbreviations for IRIs and triple patterns given in section 4 FILTER FILTER apply them to the whole translated group graph pattern In this step, we also translate graph patterns within FILTER EXISTS NOT EXISTS Let FS := empty set
For each form FILTER(expr) in the group graph pattern: In expr, replace NOT EXISTS{P} with fn:not( exists(translate(P))) exists(translate(P)) The set of filter expressions FS used later The following table gives the translation of property paths expressions from SPARQL syntax to terms in the SPARQL algebra. This applies to all elements of a property path expression recursively. The next step after this one { }) Notes: The order of forms IRI and ^IRI in negated property sets is not relevant. We introduce the following symbols: link inv alt seq ZeroOrMorePath OneOrMorePath ZeroOrOnePath NPS (for NegatedPropertySet) Syntax Form (path) Algebra (path) iri link(iri) ^path inv(path) !(:iri 1 n NPS({:iri 1 n !(^:iri 1 n inv(NPS({:iri 1 n !(:iri 1 i i+1 m alt(NPS({:iri 1 i i+1 m path1 / path2 seq(path1, path2) path1 | path2 alt(path1, path2) path* ZeroOrMorePath(path) path+ OneOrMorePath(path) path? ZeroOrOnePath(path) The previous step translated property path expressions property path patterns Notes: X and Y are RDF terms or variables. ?V is a fresh variable. P and Q are path expressions. These are only applied to property path patterns, not within property path expressions. Translations earlier in the table are applied in preference to the last translation. The final translation simply wraps any remaining property path expression to use a common form Path(...) Algebra (path) Translation X link(iri) Y X iri Y X inv(iri) Y Y iri X X seq(P, Q) Y X P ?V . ?V Q P X P Y Path(X, P, Y) Examples of the whole path translation process ( ?_V ?s :p/:q ?o ?s :p ?_V . ?s :p* ?o Path(?s, ZeroOrMorePath(link(:p)), ?o) :list rdf:rest*/rdf:first ?member Path(:list, ZeroOrMorePath(link(rdf:rest)), ?_V) . After translating property paths, any adjacent triple patterns are collected together to form a basic graph pattern BGP(triples) Next, we translate each remaining graph pattern form, recursively applying the translation process. If the form is GroupOrUnionGraphPattern Let A := undefined For each element G in the GroupOrUnionGraphPattern If A is undefined A := Translate(G) Else A := Union(A, Translate(G)) End
The result is A If the form is GraphGraphPattern If the form is GRAPH IRI GroupGraphPattern The result is Graph(IRI, Translate(GroupGraphPattern)) If the form is GRAPH Var GroupGraphPattern The result is Graph(Var, Translate(GroupGraphPattern)) If the form is GroupGraphPattern Let FS := the empty set Let G := the empty pattern, a basic graph pattern which is the empty set.
For each element E in the GroupGraphPattern
If E is of the form OPTIONAL{P} Let A := Translate(P) If A is of the form Filter(F, A2) G := LeftJoin(G, A2, F) Else G := LeftJoin(G, A, true) End End
If E is of the form MINUS{P} G := Minus(G, Translate(P)) End
If E is of the form BIND(expr AS var) G := Extend(G, var, expr) End
If E is any other form Let A := Translate(E) G := Join(G, A) End
End The result is G. If the form is InlineData The result is a multiset of solution mappings 'data'. data BindingValue UNDEF If the form is SubSelect The result is ToMultiset(Translate(SubSelect)) After the group has been translated, the filter expressions are added so they wil apply to the whole of the rest of the group: If FS is not empty Let G := output of preceding step Let X := Conjunction of expressions in FS G := Filter(X, G) End Some groups of one graph pattern become join(Z, A) Replace join(Z, A) by A Replace join(A, Z) by A The second form of a rewrite example is the first with empty group joins removed by the simplification step. Example: group with a basic graph pattern consisting of a single triple pattern: { ?s ?p ?o } Join(Z, BGP(?s ?p ?o) ) BGP(?s ?p ?o) Example: group with a basic graph pattern consisting of two triple patterns: { ?s :p1 ?v1 ; :p2 ?v2 } BGP( ?s :p1 ?v1 . ?s :p2 ?v2 ) Example: group consisting of a union of two basic graph patterns: { { ?s :p1 ?v1 } UNION {?s :p2 ?v2 } } Union(Join(Z, BGP(?s :p1 ?v1)), Union( BGP(?s :p1 ?v1) , BGP(?s :p2 ?v2) ) Example: group consisting of a union of a union and a basic graph pattern: { { ?s :p1 ?v1 } UNION {?s :p2 ?v2 } UNION {?s :p3 ?v3 } } Union( Union( Example: group consisting of a basic graph pattern and an optional graph pattern: { ?s :p1 ?v1 OPTIONAL {?s :p2 ?v2 } } LeftJoin( LeftJoin(BGP(?s :p1 ?v1), BGP(?s :p2 ?v2), true) Example: group consisting of a basic graph pattern and two optional graph patterns: { ?s :p1 ?v1 OPTIONAL {?s :p2 ?v2 } OPTIONAL { ?s :p3 ?v3 } } LeftJoin( Example: group consisting of a basic graph pattern and an optional graph pattern with a filter: { ?s :p1 ?v1 OPTIONAL {?s :p2 ?v2 FILTER(?v1<3) } } LeftJoin( LeftJoin( Example: group consisting of a union graph pattern and an optional graph pattern: { {?s :p1 ?v1} UNION {?s :p2 ?v2} OPTIONAL {?s :p3 ?v3} } LeftJoin( Example: group consisting of a basic graph pattern, a filter and an optional graph pattern: { ?s :p1 ?v1 FILTER (?v1 < 3 ) OPTIONAL {?s :p2 ?v2} } Filter( ?v1 < 3 , Example: Pattern involving BIND: { ?s :p ?v . BIND (2*?v AS ?v2) ?s :p1 ?v2 } Join( Example: Pattern involving BIND: { ?s :p ?v . {} BIND (2*?v AS ?v2) } Join( Example: Pattern involving MINUS: { ?s :p ?v . MINUS {?s :p1 ?v2 } } Minus( Example: Pattern involving a subquery: { ?s :p ?o . {SELECT DISTINCT ?o {?o ?p ?z} } } Join( In this step, we process clauses on the query level in the following order: Grouping Aggregates HAVING VALUES Select expressions Step: GROUP BY If the GROUP BY Group Step: Aggregates The aggregation step is applied as a transformation on the query level, replacing aggregate expressions in the query level with Aggregation() algebraic expressions. The transformation for query levels that use any aggregates is given below: Let A := the empty sequence Let Q := the query level being evaluated Let P := the algebra translation of the GroupGraphPattern of the query level Let E := [], a list of pairs of the form (variable, expression)
If Q contains GROUP BY exprlist Let G := Group(exprlist, P) Else If Q contains an aggregate in SELECT, HAVING, ORDER BY Let G := Group((1), P) Else skip the rest of the aggregate step End
Global i := 1 # Initially 1 for each query processed
For each (X AS Var) in SELECT, each HAVING(X), and each ORDER BY X in Q For each unaggregated variable V in X Replace V with Sample(V) End For each aggregate R(args ; scalarvals) now in X # note scalarvals may be omitted, then it's equivalent to the empty set A i i i i i i-1 Note: agg i Example: PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT (SUM(?val) AS ?sum) (COUNT(?a) AS ?count) WHERE { ?a rdf:value ?val . } GROUP BY ?a The SUM expression becomes agg 1 2 Let G := Group((?a), BGP(?a rdf:value ?val)) A 1 A 2 A 1 2 The HAVING expression is evaluated using the same rules as FILTER(). Note that, due to the logic position in which the HAVING clause is evaluated, expressions projected by the SELECT clause are not visible to the HAVING clause. Let Q := the query level being evaluated Let P := the algebra translation of the query level so far
For each HAVING(E) in Q P := Filter(E, P) End If the query has a trailing VALUES clause: Let P := the algebra translation of the query level so far P := Join(P, ToMultiSet(data)) where data The translatation of the data is the same as for inline data Step: Select expressions We have two forms of the abstract syntax to consider: SELECT selItem ... { pattern } SELECT * { pattern } Let X := algebra from earlier steps Let VS := list of all variables visible in the pattern, so restricted by sub-SELECT projected variables and GROUP BY variables. Not visible: only in filter, exists/not exists, masked by a subselect, non-projected GROUP variables, only in the right hand side of MINUS
Let PV := {}, a set of variable names Note, E is a list of pairs of the form (variable, expression), defined in section 18.2.4 selItem ... The syntax error arises for use of a variable as the named target of AS (e.g. ... AS ?x) when the variable is used inside the WHERE clause of the SELECT or if already used as the traget of AS in this SELECT expression. Solutions modifiers apply to the processing of a SPARQL query after pattern matching. The solution modifiers are applied to a query in the following order: Order by Projection Distinct Reduced Offset Limit Step: ToList ToList turns a multiset into a sequence with the same elements and cardinality. There is no implied ordering to the sequence; duplicates need not be adjacent. Let M := ToList(Pattern) If the query string has an ORDER BY clause M := OrderBy(M, list of order comparators) The set of projection variables, PV processing of SELECT expressions M := Project(M, PV) where vars is the set of variables mentioned in the SELECT clause or all named variables that are in-scope If the query contains DISTINCT, M := Distinct(M) If the query contains REDUCED, M := Reduced(M) If the query contains "OFFSET start" or "LIMIT length" M := Slice(M, start, length) start defaults to 0 length defaults to (size(M)-start). The overall abstract query is M. When matching graph patterns, the possible solutions form a multiset multiset bag Write μ for solution mappings. Write μ 0 0 Write Ω 0 0, Write μ(x) for the solution mapping variable x to RDF term t : { (x, t) } Write Ω(x) for the multiset consisting of exactly μ(?x->t), that is, { { (x, t) } } with cardinality 1. Definition: Compatible Mappings Two solution mappings μ 1 2 1 2 1 2 Here, μ 1 2 1 2 If μ 1 2 1 2 1 2 1 2 Write card[Ω](μ) for the cardinality of solution mapping μ in a multiset of mappings Ω. A basic graph pattern is matched against the active graph for that part of the query. Basic graph patterns can be instantiated by replacing both variables and blank nodes by terms, giving two notions of instance. Blank nodes are replaced using an RDF instance mapping Definition: Pattern Instance Mapping A Pattern Instance Mapping For a BGP 'x', P(x) denotes the result of replacing blank nodes b in x for which σ is defined with σ(b) and all variables v in x for which μ is defined with μ(v). Any pattern instance mapping defines a unique solution mapping and a unique RDF instance mapping obtained by restricting it to query variables and blank nodes respectively. Definition: Basic Graph Pattern Matching Let BGP be a basic graph pattern and let G be an RDF graph. μ is a solution card[Ω](μ) = card[Ω](number of distinct RDF instance mappings, σ, such that P = μ(σ) is a pattern instance mapping and P(BGP) is a subgraph of G). If a basic graph pattern is the empty set, then the solution is Ω 0 This definition allows the solution mapping to bind a variable in a basic graph pattern, BGP, to a blank node in G. Since SPARQL treats blank node identifiers in a results format document
( SPARQL Query Results XML Format SPARQL 1.1 Query Results JSON Format SPARQL 1.1 Query Results CSV and TSV Formats scoping graph, Since RDF blank nodes allow infinitely many redundant solutions for many patterns, there can be infinitely many pattern solutions (obtained by replacing blank nodes by different blank nodes). It is necessary, therefore, to somehow delimit the solutions for a basic graph pattern. SPARQL uses the subgraph match criterion to determine the solutions of a basic graph pattern. There is one solution for each distinct pattern instance mapping from the basic graph pattern to a subset of the active graph. This is optimized for ease of computation rather than redundancy elimination. It allows query results to contain redundancies even when the active graph of the dataset is lean This section defines the evaluation of property path patterns translation of property path expressions All remaining property path expressions are present in the algebra in the form Path(X, path, Y) (:p/:q)* ZeroOrMorePath(seq(link(:p), link(:q))) Notation Write eval(Path(X, PP, Y)) for the evaluation of the property path patterns. This produces a multiset of solution mappings μ, each solution mapping having a binding for variables used (each of X and Y can be a variable). Some operators only produce a set of solution mappings. Write Var(x 1 2 n i i for the variables in x 1 2 n Write x:term when x x:var when x x:path when x All evaluation is carried out by matching the active graph Definition: Evaluation of Predicate Property Path Let Path(X, link(iri), Y) be an predicate inverse property path pattern, using some IRI iri. eval(Path(X, link(iri), Y)) = evaluation of basic graph pattern If both X and Y are variables, this is the same as: eval(Path(X:var, link(iri), Y:var)) = { (X, xn) (Y, yn) | xn and yn are RDF terms and triple (xn iri yn) is in the active graph } If X is a variable and Y an RDF term: eval(Path(X:var, link(iri), Y:term)) = { (X, xn) | xn is an RDF term and triple (xn iri Y) is in the active graph } If X is an RDF term and Y is a variable: eval(Path(X:term, link(iri), Y:var)) = { (Y, yn) | yn is an RDF term and triple (X iri yn) is in the active graph } If both X and Y are RDF terms: eval(Path(X:term, link(iri), Y:term)) = { μ 0 0 Informally, evaluating a Predicate Property Path is the same as executing a subquery SELECT * { X P Y Definition: Evaluation of Inverse Property Path Let P be a property path expression, then: eval(Path(X, inv(P), Y)) = eval(Path(Y, P, X)) Definition: Evaluation of Sequence Property Path Let P and Q be property path expressions. Let V be a fresh variable. A = Join( eval(Path(X, P, V)), eval(Path(V, Q, Y)) ) eval(Path(X, seq(P,Q), Y)) = Project(A, Var(X,Y)) Informally, this is the same as: SELECT * { X P _:a . _:a Q Y } using the fact that a blank node _:a SELECT * Definition: Evaluation of Alternative Property Path Let P and Q be property path expressions. eval(Path(X, alt(P,Q), Y)) = Union(eval(Path(X, P, Y)), eval(Path(X, Q, Y))) Informally, this is the same as: SELECT * { { X P Y } UNION { X Q Y } } Definition: Node set of a graph The node set of a graph G, nodes(G), is: nodes(G) = { n | n is an RDF term that is used as a subject or object of a triple of G} Definition: Evaluation of ZeroOrOnePath eval(Path(X:term, ZeroOrOnePath(P), Y:var)) = { (Y, yn) | yn = X or {(Y, yn)} in eval(Path(X,P,Y)) } eval(Path(X:var, ZeroOrOnePath(P), Y:term)) = { (X, xn) | xn = Y or {(X, xn)} in eval(Path(X,P,Y)) } eval(Path(X:term, ZeroOrOnePath(P), Y:term)) = { {} } if X = Y or eval(Path(X,P,Y)) is not empty { } othewise eval(Path(X:var, ZeroOrOnePath(P), Y:var)) = { (X, xn) (Y, yn) | either (yn in nodes(G) and xn = yn) or {(X,xn), (Y,yn)} in eval(Path(X,P,Y)) } We define an auxillary function, ALP, used in the definitions of ZeroOrMorePath and OneOrMorePath. Note that the algorithm given here serves to specify the feature. An implementation is free to implement evaluation by any method that produces the same results for the query overall. The ZeroOrMorePath and OneOrMorePath forms return matches based on distinct nodes connected by the path. The matching algorithm is based on following all paths, and detecting when a graph node (subject or object), has been already visited on the path. Informally, this algorithm attempts to extend the multiset of results by one application of path Definition: Function ALP Let eval(x:term, path) be the evaluation of 'path', starting at RDF term x, and returning a multiset of RDF terms reached by repeated matches of path.
ALP(x:term, path) = Let V = empty multiset ALP(x:term, path, V) return is V
# V is the set of nodes visited
ALP(x:term, path, V:set of RDF terms) = if ( x in V ) return add x to V X = eval(x,path) For n:term in X ALP(n, path, V) End Definition: Evaluation of ZeroOrMorePath eval(Path(X:term, ZeroOrMorePath(path), vy:var)) = { { (vy, n) } | n in ALP(X, path) }
eval(Path(vx:var, ZeroOrMorePath(path), vy:var)) = { { (vx, t), (vy, n) } | t in nodes(G), (vy, n) in eval(Path(t, ZeroOrMorePath(path), vy)) }
eval(Path(vx:var, ZeroOrMorePath(path), y:term)) = eval(Path(y:term, ZeroOrMorePath(inv(path)), vx:var))
eval(Path(x:term, ZeroOrMorePath(path), y:term)) = { { } } if { (vy:var,y) } in eval(Path(x, ZeroOrMorePath(path) vy) { } otherwise Definition: Evaluation of OneOrMorePath eval(Path(X, OneOrMorePath(path), Y)) # For OneOrMorePath, we take one step of the path then start # recording nodes for results.
eval(Path(x:term, OneOrMorePath(path), vy:var)) = Let X = eval(x, path) Let V = the empty multiset For n in X ALP(n, path, V) End result is V
eval(Path(vx:var, OneOrMorePath(path), vy:var)) = { { (vx, t), (vy, n) } | t in nodes(G), (vy, n) in eval(Path(t, OneOrMorePath(path), vy)) }
eval(Path(vx:var, OneOrMorePath(path), y:term)) = eval(Path(y:term, OneOrMorePath(inv(path)), vx))
eval(Path(x:term, OneOrMorePath(path), y:term)) = { { } } if { (vy:var, y) } in eval(Path(x, OneOrMorePath(path), vy)) { } otherwise Definition: Evaluation of NegatedPropertySet Write μ' as the extension of a solution mapping: μ'(μ,x) = μ(x) if x is a variable μ'(μ,t) = t if t is a RDF term Let x and y be variables or RDF terms, and S a set of IRIs:
eval(Path(x, NPS(S), y)) = { μ | ∃ triple(μ'(μ,x), p, μ'(μ,y)) in G, such that the IRI of p ∉ S } For each remaining symbol in a SPARQL abstract query, we define an operator for evaluation. The SPARQL algebra operators of the same name are used to evaluate SPARQL abstract query nodes as described in the section " Evaluation Semantics Definition: Filter Let Ω be a multiset of solution mappings and expr be an expression. We define: Filter(expr, Ω, D(G)) = { μ | μ in Ω and expr(μ) is an expression that has an effective boolean value of true } card[Filter(expr, Ω, D(G))](μ) = card[Ω](μ) Note that evaluating an exists(pattern) evaluation of filter Definition: Join Let Ω 1 2 Join(Ω 1 2 1 2 1 1 2 2 1 2 card[Join(Ω 1 2 1 2 1 1 2 2 1 2 1 2 1 1 2 2 It is possible that a solution mapping μ in a Join can arise in different solution mappings, μ 1 2 Definition: Diff Let Ω 1 2 Diff(Ω 1 2 1 2 card[Diff(Ω 1 2 1 Diff is used internally for the definition of LeftJoin. Definition: LeftJoin Let Ω 1 2 LeftJoin(Ω 1 2 1 2 1 2 card[LeftJoin(Ω 1 2 1 2 1 2 Written in full that is: LeftJoin(Ω 1 2 1, 2 1 1 2 2 1 2 1 2 1 1 1 2 2 1 2 2 1 1 1 2 2 1 2 1 2 As these are distinct, the cardinality of LeftJoin is cardinality of these individual components of the definition. Definition: Union Let Ω 1 2 Union(Ω 1 2 1 2 card[Union(Ω 1 2 1 2 Definition: Minus Let Ω 1 2 Minus(Ω 1 2 1 2 card[Minus(Ω 1 2 1 The additional restriction on dom(μ) and dom(μ') is added because otherwise if there is a solution mapping in Ω 2 1 1 2 2 P MINUS {} P Definition: Extend Let μ be a solution mapping, Ω a multiset of solution mappings, var expr expression Extend(μ, var, expr) = μ ∪ { (var,value) | var not in dom(μ) and value = expr(μ) } Extend(μ, var, expr) = μ if var not in dom(μ) and expr(μ) is an error Extend is undefined when var in dom(μ). Extend(Ω, var, expr) = { Extend(μ, var, expr) | μ in Ω } Write [ x | C ] for a sequence of elements where C is a condition on x. Write card[L](x) to be the cardinality of x in L. Definition: ToList Let Ω be a multiset of solution mappings. We define: ToList(Ω) = a sequence of mappings μ in Ω in any order, with card[Ω](μ) occurrences of μ card[ToList(Ω)](μ) = card[Ω](μ) Definition: OrderBy Let Ψ be a sequence of solution mappings. We define: OrderBy card[OrderBy(Ψ, condition)](μ) = card[Ψ](μ) Definition: Project Let Ψ be a sequence of solution mappings and PV a set of variables. For mapping μ, write Proj(μ, PV) to be the restriction of μ to variables in PV. Project(Ψ, PV) = [ Proj(Ψ[μ], PV) | μ in Ψ ] card[Project(Ψ, PV)](μ) = card[Ψ](μ) The order of Project(Ψ, PV) must preserve any ordering given by OrderBy. Definition: Distinct Let Ψ be a sequence of solution mappings. We define: Distinct(Ψ) = [ μ | μ in Ψ ] card[Distinct(Ψ)](μ) = 1 The order of Distinct(Ψ) must preserve any ordering given by OrderBy. Definition: Reduced Let Ψ be a sequence of solution mappings. We define: Reduced(Ψ) = [ μ | μ in Ψ ] card[Reduced(Ψ)](μ) is between 1 and card[Ψ](μ) The order of Reduced(Ψ) must preserve any ordering given by OrderBy. The Reduced solution sequence modifier does not guarantee a defined cardinality. Definition: Slice Let Ψ be a sequence of solution mappings. We define: Slice Definition: ToMultiSet Let Ψ be a solution sequence. We define: ToMultiSet(Ψ) = { μ | μ in Ψ } card[ToMultiSet(Ψ)](μ) = card[Ψ](μ) ListEval is a function which is used to evaluate a list of expressions against a solution and return a list of the resulting values. Definition: ToMultiset ToMultiset turns a sequence into a multiset with the same elements and cardinality as the sequence. The order of the sequence has no effect on the resulting multiset, and duplicates are preserved. Definition: Exists exists(pattern) is a function that returns true if the pattern evaluates Group is a function which groups a solution sequence into multiple solutions, based on some attribute of the solutions. Definition: Group Group evaluates a list of expressions against a solution sequence, producing a set of partial functions from keys to solution sequences. Group(exprlist, Ω) = { ListEval(exprlist, μ) → { μ' | μ' in Ω, ListEval(exprlist, μ) = ListEval(exprlist, μ') } | μ in Ω } Definition: ListEval ListEval((expr 1 n 1 n i i ListEval retains errors resulting from the evaluation of the list elements. Note that, although the result of a ListEval can be an error, and errors may be used to group, solutions containing error values are removed at projection time. ListEval((unbound), μ) = (error), as the evaluation of an unbound expression is an error. Aggregation, a function which calculates a scalar value as an output of the aggregate expression. It is used in the SELECT clause, the HAVING evaluation process, and in ORDER BY (where required). Aggregation calculates aggregated values over groups of solutions, using set functions. Definition: Aggregation Let exprlist func scalarvals 1 1 m m Aggregation applies the set function func to the given multiset and produces a single value for each key and partition of solutions for that key. Aggregation(exprlist, func, scalarvals, { key 1 1 m m 1 1 m m where Special Case: COUNT * card[Ω] card[Distinct(Ω)] DISTINCT scalarvals GROUP_CONCAT(?x ; separator="|") All aggregates may have the DISTINCT Example Given a solution multiset (Ω) with the following values: solution ?x ?y ?z μ 1 1 2 3 μ 2 1 3 4 μ 3 2 5 6 And the query expression SELECT (ex:agg(?y, ?z) AS ?agg) WHERE { ?x ?y ?z } GROUP BY ?x. We produce G = Group((?x), Ω) = { ( (1), { μ 1 2 3 And so Aggregation((?y, ?z), ex:agg, {}, G) = Definition: AggregateJoin Let S 1 n i Let K = { key | key in dom(S j 1 n 1 1 n n i i Flatten is a function which is used to collapse multisets of lists into a multiset, so for example { (1, 2), (3, 4) } becomes { 1, 2, 3, 4 }. Definition: Flatten The Flatten(M) function takes a multiset of lists, M {(L 1 2 The set functions which underlie SPARQL aggregates all have a common signature: SetFunc(M), or SetFunc(M, scalarvals) where M is a multiset of lists, and scalarvals is one or more scalar values that are passed to the set function indirectly via the ( ... ; key=value ) syntax for aggregates in the SPARQL grammar. The only use of this that is supported by the built-in aggregates in SPARQL Query 1.1 is GROUP_CONCAT GROUP_CONCAT(?x ; separator=", ") Note that the name "Set Function" is somewhat historical — the arguments to set functions are in fact multisets. The name is retained due to the commonality with SQL Set Functions, which also operate over multisets. The set functions defined in this document are Count, Sum, Min, Max, Avg, GroupConcat, and Sample — corresponding to the aggregates COUNT SUM MIN MAX AVG GROUP_CONCAT SAMPLE Count is a SPARQL set function which counts the number of times a given expression has a bound, and non-error value within the aggregate group. Definition: Count N = Flatten(M) remove error elements from N Count(M) = card[N] Sum is a SPARQL set function that will return the numeric value obtained by summing the values within the aggregate group. Type promotion happens as per the op:numeric-add function, applied transitively, (see definition below) so the value of SUM(?x), in an aggregate group where ?x has values 1 (integer), 2.0e0 (float), and 3.0 (decimal) will be 6.0 (float). Definition: Sum The Sum set function is used by the SUM Sum(M) = Sum(ToList(Flatten(M))). Sum(S) = op:numeric-add(S 1 2..n 1 In this way, Sum({1, 2, 3}) = op:numeric-add(1, op:numeric-add(2, op:numeric-add(3, 0))). Definition: Avg Avg(M) = "0"^^xsd:integer, where Count(M) = 0 Avg(M) = Sum(M) / Count(M), where Count(M) > 0 For example, Avg({1, 2, 3}) = Sum({1, 2, 3})/Count({1, 2, 3}) = 6/3 = 2. Min is a SPARQL set functions that returns the minimum value from a group respectively. It makes use of the SPARQL ORDER BY ordering definition, to allow ordering over arbitrarily typed expressions. Definition: Min Min(M) = Min(ToList(Flatten(M))) Min({}) = error. The flattened multiset of values passed as an argument is converted to a sequence S, this sequence is ordered as per the ORDER BY ASC Min(S) = S 0 Max is a SPARQL set function that return the maximum value from a group respectively. It makes use of the SPARQL ORDER BY ordering definition, to allow ordering over arbitrarily typed expressions. Definition: Max Max(M) = Max(ToList(Flatten(M))) Max({}) = error. The multiset of values passed as an argument is converted to a sequence S, this sequence is ordered as per the ORDER BY DESC Max(S) = S 0 GroupConcat is a set function which performs a string concatenation across the values of an expression with a group. The order of the strings is not specified. The separator character used in the concatenation may be given with the scalar argument SEPARATOR. Definition: GroupConcat If the "separator" scalar argument is absent from GROUP_CONCAT then it is taken to be the "space" character, unicode codepoint U+0020. The multiset of values, M passed as an argument is converted to a sequence S. GroupConcat(M, scalarvals) = GroupConcat(Flatten(M), scalarvals("separator")) GroupConcat(S, sep) = "", where | | GroupConcat(S, sep) = CONCAT("", S 0 | | GroupConcat(S, sep) = CONCAT(S 0 1..n-1 | | For example, GroupConcat({"a", "b", "c"}, {"separator" → "."}) = "a.b.c". Sample is a set function which returns an arbitrary value from the multiset passed to it. Definition: Sample Sample(M) = v, where v in Flatten(M) Sample({}) = error For example, given Sample({"a", "b", "c"}), "a", "b", and "c" are all valid return values. Note that Sample() is not required to be deterministic for a given input, the only restriction is that the output value must be present in the input multiset. We define eval(D(G), algebra expression) as the evaluation of an algebra expression with respect to a dataset D having active graph G. The active graph is initially the default graph. D : a dataset D(G) : D a dataset with active graph G (the one patterns match against) D[i] : The graph with IRI i in dataset D P, P1, P2 : graph patterns L : a solution sequence F : an expression Definition: Evaluation of a Basic Graph Pattern eval(D(G), BGP) = multiset of solution mappings See section Basic Graph Patterns Definition: Evaluation of a Property Path Pattern eval(D(G), Path(X, path, Y)) = multiset of solution mappings See section Property Path Expresions Definition: Evaluation of Filter eval(D(G), Filter(F, P)) = Filter(F, eval(D(G),P), D(G)) 'substitute' is a filter function in support of the evaluation of EXISTS NOT EXISTS exists Definition: Substitute Let μ be a solution mapping. substitute( pattern pattern Definition: Evaluation of Exists Let μ be the current solution mapping for a filter and P a graph pattern: The value exists(P), given D(G) is true if and only if eval(D(G), substitute(P, μ)) is a non-empty sequence. Definition: Evaluation of Join eval(D(G), Join(P1, P2)) = Join(eval(D(G), P1), eval(D(G), P2)) Definition: Evaluation of LeftJoin eval(D(G), LeftJoin(P1, P2, F)) = LeftJoin(eval(D(G), P1), eval(D(G), P2), F) Definition: Evaluation of Union eval(D(G), Union(P1,P2)) = Union(eval(D(G), P1), eval(D(G), P2)) Definition: Evaluation of Graph if IRI is a graph name in D eval(D(G), Graph(IRI,P)) = eval(D(D[IRI]), P) if IRI is not a graph name in D eval(D(G), Graph(IRI,P)) = the empty multiset eval(D(G), Graph(var,P)) = Let R be the empty multiset foreach IRI i in D R := Union(R, Join( eval(D(D[i]), P) , Ω(?var->i) ) the result is R The evaluation of graph uses the SPARQL algebra union operator. The cardinality of a solution mapping is the sum of the cardinalities of that solution mapping in each join operation. Definition: Evaluation of Group eval(D(G), Group(exprlist, P)) = Group(exprlist, eval(D(G), P)) Definition: Evaluation of Aggregation eval(D(G), Aggregation(exprlist, func, scalarvals, P)) = Aggregation(exprlist, func, scalarvals, eval(D(G), P)) Definition: Evaluation of AggregateJoin eval(D(G), AggregateJoin(A 1 n 1 n Note that if eval(D(G), A i Definition: Evaluation of Extend eval(D(G), Extend(P, var, expr)) = Extend(eval(D(G), P), var, expr) Definition: Evaluation of ToList eval(D(G), ToList(P)) = ToList(eval(D(G), P)) Definition: Evaluation of Distinct eval(D(G), Distinct(L)) = Distinct(eval(D(G), L)) Definition: Evaluation of Reduced eval(D(G), Reduced(L)) = Reduced(eval(D(G), L)) Definition: Evaluation of Project eval(D(G), Project(L, vars)) = Project(eval(D(G), L), vars) Definition: Evaluation of OrderBy eval(D(G), OrderBy(L, condition)) = OrderBy(eval(D(G), L), condition) Definition: Evaluation of ToMultiSet eval(D(G), ToMultiSet(L)) = ToMultiSet(eval(D), M)) Definition: Evaluation of Slice eval(D(G), Slice(L, start, length)) = Slice(eval(D(G), L), start, length) The overall SPARQL design can be used for queries which assume a more elaborate form of entailment than simple entailment, by re-writing the matching conditions for basic graph patterns. Since it is an open research problem to state such conditions in a single general form which applies to all forms of entailment and optimally eliminates needless or inappropriate redundancy, this document only gives necessary conditions which any such solution should satisfy. These will need to be extended to full definitions for each particular case. Basic graph patterns stand in the same relation to triple patterns that RDF graphs do to RDF triples, and much of the same terminology can be applied to them. In particular, two basic graph patterns are said to be equivalent An entailment regime a subset of RDF graphs called well-formed an entailment Detailed definitions for querying various entailment regimes can be found in SPARQL 1.1 Entailment Regimes Some entailment regimes can categorize some RDF graphs as inconsistent. For example, the RDF graph: _:x rdf:type xsd:string . _:x rdf:type xsd:decimal . is D-inconsistent when D contains the XSD datatypes. The effect of a query on an inconsistent graph is not covered by this specification, but must be specified by the particular SPARQL extension. An entailment regime E must provide conditions on basic graph pattern evaluation such that for any basic graph pattern BGP, any RDF graph G, and any evaluation that satisfies the conditions, the resulting multiset of solutions is uniquely determined up to RDF graph equivalence. We denote the multiset of solutions from evaluating BGP over G using E with Eval-E(G, BGP). For any E-consistent active graph AG, the entailment regime E uniquely specifies a scoping graph A set of well-formed graphs for E is specified such that, for any basic graph pattern BGP, scoping graph SG, and solution mapping μ in Eval-E(SG, BGP), the graph μ(BGP) is well-formed for E. For any basic graph pattern BGP and scoping graph SG, if μ 1 n 1 n SG E-entails (SG union μ 1 1 n n These conditions do not fully determine the set of possible answers, since RDF allows unlimited amounts of redundancy. In addition, therefore, the following must hold. Entailment regimes should provide conditions to prevent trivial infinite solution multisets as appropriate to the regime. (a) SG will often be graph equivalent to AG, but restricting this to E-equivalence allows some forms of normalization, for example elimination of semantic redundancies, to be applied to the source documents before querying. (b) The construction in condition 3 ensures that any blank nodes introduced by the solution mapping are used in a way which is internally consistent with the way that blank nodes occur in SG. This ensures that blank node identifiers occur in more than one answer in an answer set only when the blank nodes so identified are indeed identical in SG. If the extension does not allow bindings to blank nodes, then this condition can be simplified to the condition: SG E-entails μ(BGP) for each solution mapping μ. (c) These conditions do not impose the SPARQL requirement that SG shares no blank nodes with AG or BGP. In particular, it allows SG to actually be AG. This allows query protocols in which blank node identifiers retain their meaning between the query and the source document, or across multiple queries. Such protocols are not supported by the current SPARQL protocol specification, however. (d) Since conditions 1 to 3 are only necessary conditions on answers, condition 4 allows cases where the set of legal answers can be restricted in various ways. (e) None of these conditions refer explicitly to instance mappings on blank nodes in BGP. For some entailment regimes, the existential interpretation of blank nodes cannot be fully captured by the existence of a single instance mapping. These conditions allow such regimes to give blank nodes in query patterns a 'fully existential' reading. It is straightforward to show that SPARQL satisfies these conditions for the case where E is simple entailment, given that the SPARQL condition on SG is that it is graph-equivalent to AG but shares no blank nodes with AG or BGP (which satisfies the first condition). The only condition which is nontrivial is (3). For every solution mapping μ i i i i i i i i i i i i i i i i i i i P 1 1 n n 1 1 1 n n n 1 n 1 1 n n since the domains of the σ i SG union [ σ 1 n 1 1 n n 1 n 1 1 n n i.e. SG union μ 1 1 n n has an instance which is a subgraph of SG, so is simply entailed by SG by the RDF interpolation lemma RDF-MT The SPARQL grammar covers both SPARQL Query and SPARQL Update A SPARQL Request String CHARMOD A SPARQL Query String QueryUnit A SPARQL Update String UpdateUnit For compatibility with future versions of Unicode, the characters in this string may include Unicode codepoints that are unassigned as of the date of this publication (see Identifier and Pattern Syntax UNIID [^<>'{}|^`] #x0 - #x10FFFF A SPARQL Query String is processed for codepoint escape sequences before parsing by the grammar defined in EBNF below. The codepoint escape sequences for a SPARQL query string are: 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+0 to U+10FFFF inclusive corresponding to the encoded hexadecimal value. where HEX HEX Examples: <ab\u00E9xy> # Codepoint 00E9 is Latin small e with acute - é \u03B1:a # Codepoint x03B1 is Greek small alpha - α a\u003Ab # a:b -- codepoint x3A is colon Codepoint escape sequences can appear anywhere in the query string. They are processed before parsing based on the grammar rules and so may be replaced by codepoints with significance in the grammar, such as " : 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 \u0020 White space (production WS For example: ?a<?b&&?c>?d is the token sequence variable ' ?a <?b&&?c> ?d && < > Comments in SPARQL queries take the form of ' # 0x0D 0x0A Text matched by the IRIREF PrefixedName RFC3987 IRIREF <abc#def> IRIREF <abc##def> Base IRIs declared with the BASE PREFIX Syntax of IRI Terms BASE PREFIX Blank nodes can not be used in: DELETE WHERE DELETE DATA a DeleteClause in a SPARQL Update request Blank node labels are scoped to the SPARQL Request String The same blank node label can not be used in: two basic graph patterns in a SPARQL Query two WHERE two INSERT DATA Note that the same blank node label can occur in different QuadPattern SPARQL Update In addition to the codepoint escape sequences string STRING_LITERAL1 STRING_LITERAL2 STRING_LITERAL_LONG1 STRING_LITERAL_LONG2 Escape Unicode code point '\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) Examples: "abc\n" "xy\rz" 'xy\tz' The EBNF notation used in the grammar is defined in Extensible Markup Language (XML) 1.1 [ XML11 Notation Notes: Keywords are matched in a case-insensitive manner with the exception of the keyword ' a rdf:type http://www.w3.org/1999/02/22-rdf-syntax-ns#type Escape sequences are case sensitive. When tokenizing the input and choosing grammar rules, the longest match is chosen. The SPARQL grammar is LL(1) when the rules with uppercased names are used as terminals. There are two entry points into the grammar: QueryUnit UpdateUnit In signed numbers, no white space is allowed between the sign and the number. The AdditiveExpression The tokens INSERT DATA , , The QuadData QuadPattern Quads QuadData INSERT DATA DELETE DATA Blank node syntax is not allowed in DELETE WHERE DeleteClause DELETE DELETE DATA Rules for limiting the use of blank node labels are given in section 19.6 The number of variables in the variable list of VALUES DataBlock Variables introduced by AS SELECT in-scope The variable assigned in a BIND TriplesBlock GroupGraphPattern Aggregate functions can be one of the built-in keywords for aggregates function call SELECT HAVING ORDER BY Only custom aggregate functions use the DISTINCT function call [1] QueryUnit ::= Query [2] Query ::= Prologue SelectQuery ConstructQuery DescribeQuery AskQuery ValuesClause [3] UpdateUnit ::= Update [4] Prologue ::= ( BaseDecl PrefixDecl [5] BaseDecl ::= 'BASE' IRIREF [6] PrefixDecl ::= 'PREFIX' PNAME_NS IRIREF [7] SelectQuery ::= SelectClause DatasetClause WhereClause SolutionModifier [8] SubSelect ::= SelectClause WhereClause SolutionModifier ValuesClause [9] SelectClause ::= 'SELECT' 'DISTINCT' 'REDUCED' Var '(' Expression 'AS' Var ')' '*' [10] ConstructQuery ::= 'CONSTRUCT' ConstructTemplate DatasetClause WhereClause SolutionModifier DatasetClause 'WHERE' '{' TriplesTemplate '}' SolutionModifier [11] DescribeQuery ::= 'DESCRIBE' VarOrIri '*' DatasetClause WhereClause SolutionModifier [12] AskQuery ::= 'ASK' DatasetClause WhereClause SolutionModifier [13] DatasetClause ::= 'FROM' DefaultGraphClause NamedGraphClause [14] DefaultGraphClause ::= SourceSelector [15] NamedGraphClause ::= 'NAMED' SourceSelector [16] SourceSelector ::= iri [17] WhereClause ::= 'WHERE' GroupGraphPattern [18] SolutionModifier ::= GroupClause HavingClause OrderClause LimitOffsetClauses [19] GroupClause ::= 'GROUP' 'BY' GroupCondition [20] GroupCondition ::= BuiltInCall FunctionCall '(' Expression 'AS' Var ')' Var [21] HavingClause ::= 'HAVING' HavingCondition [22] HavingCondition ::= Constraint [23] OrderClause ::= 'ORDER' 'BY' OrderCondition [24] OrderCondition ::= ( ( 'ASC' 'DESC' BrackettedExpression Constraint Var [25] LimitOffsetClauses ::= LimitClause OffsetClause OffsetClause LimitClause [26] LimitClause ::= 'LIMIT' INTEGER [27] OffsetClause ::= 'OFFSET' INTEGER [28] ValuesClause ::= ( 'VALUES' DataBlock [29] Update ::= Prologue Update1 ';' Update [30] Update1 ::= Load Clear Drop Add Move Copy Create InsertData DeleteData DeleteWhere Modify [31] Load ::= 'LOAD' 'SILENT' iri 'INTO' GraphRef [32] Clear ::= 'CLEAR' 'SILENT' GraphRefAll [33] Drop ::= 'DROP' 'SILENT' GraphRefAll [34] Create ::= 'CREATE' 'SILENT' GraphRef [35] Add ::= 'ADD' 'SILENT' GraphOrDefault 'TO' GraphOrDefault [36] Move ::= 'MOVE' 'SILENT' GraphOrDefault 'TO' GraphOrDefault [37] Copy ::= 'COPY' 'SILENT' GraphOrDefault 'TO' GraphOrDefault [38] InsertData ::= 'INSERT DATA' QuadData [39] DeleteData ::= 'DELETE DATA' QuadData [40] DeleteWhere ::= 'DELETE WHERE' QuadPattern [41] Modify ::= ( 'WITH' iri DeleteClause InsertClause InsertClause UsingClause 'WHERE' GroupGraphPattern [42] DeleteClause ::= 'DELETE' QuadPattern [43] InsertClause ::= 'INSERT' QuadPattern [44] UsingClause ::= 'USING' iri 'NAMED' iri [45] GraphOrDefault ::= 'DEFAULT' 'GRAPH' iri [46] GraphRef ::= 'GRAPH' iri [47] GraphRefAll ::= GraphRef 'DEFAULT' 'NAMED' 'ALL' [48] QuadPattern ::= '{' Quads '}' [49] QuadData ::= '{' Quads '}' [50] Quads ::= TriplesTemplate QuadsNotTriples '.' TriplesTemplate [51] QuadsNotTriples ::= 'GRAPH' VarOrIri '{' TriplesTemplate '}' [52] TriplesTemplate ::= TriplesSameSubject '.' TriplesTemplate [53] GroupGraphPattern ::= '{' SubSelect GroupGraphPatternSub '}' [54] GroupGraphPatternSub ::= TriplesBlock GraphPatternNotTriples '.' TriplesBlock [55] TriplesBlock ::= TriplesSameSubjectPath '.' TriplesBlock [56] GraphPatternNotTriples ::= GroupOrUnionGraphPattern OptionalGraphPattern MinusGraphPattern GraphGraphPattern ServiceGraphPattern Filter Bind InlineData [57] OptionalGraphPattern ::= 'OPTIONAL' GroupGraphPattern [58] GraphGraphPattern ::= 'GRAPH' VarOrIri GroupGraphPattern [59] ServiceGraphPattern ::= 'SERVICE' 'SILENT' VarOrIri GroupGraphPattern [60] Bind ::= 'BIND' '(' Expression 'AS' Var ')' [61] InlineData ::= 'VALUES' DataBlock [62] DataBlock ::= InlineDataOneVar InlineDataFull [63] InlineDataOneVar ::= Var '{' DataBlockValue '}' [64] InlineDataFull ::= ( NIL '(' Var ')' '{' '(' DataBlockValue ')' NIL '}' [65] DataBlockValue ::= iri RDFLiteral NumericLiteral BooleanLiteral 'UNDEF' [66] MinusGraphPattern ::= 'MINUS' GroupGraphPattern [67] GroupOrUnionGraphPattern ::= GroupGraphPattern 'UNION' GroupGraphPattern [68] Filter ::= 'FILTER' Constraint [69] Constraint ::= BrackettedExpression BuiltInCall FunctionCall [70] FunctionCall ::= iri ArgList [71] ArgList ::= NIL '(' 'DISTINCT' Expression ',' Expression ')' [72] ExpressionList ::= NIL '(' Expression ',' Expression ')' [73] ConstructTemplate ::= '{' ConstructTriples '}' [74] ConstructTriples ::= TriplesSameSubject '.' ConstructTriples [75] TriplesSameSubject ::= VarOrTerm PropertyListNotEmpty TriplesNode PropertyList [76] PropertyList ::= PropertyListNotEmpty [77] PropertyListNotEmpty ::= Verb ObjectList ';' Verb ObjectList [78] Verb ::= VarOrIri 'a' [79] ObjectList ::= Object ',' Object [80] Object ::= GraphNode [81] TriplesSameSubjectPath ::= VarOrTerm PropertyListPathNotEmpty TriplesNodePath PropertyListPath [82] PropertyListPath ::= PropertyListPathNotEmpty [83] PropertyListPathNotEmpty ::= ( VerbPath VerbSimple ObjectListPath ';' VerbPath VerbSimple ObjectList [84] VerbPath ::= Path [85] VerbSimple ::= Var [86] ObjectListPath ::= ObjectPath ',' ObjectPath [87] ObjectPath ::= GraphNodePath [88] Path ::= PathAlternative [89] PathAlternative ::= PathSequence '|' PathSequence [90] PathSequence ::= PathEltOrInverse '/' PathEltOrInverse [91] PathElt ::= PathPrimary PathMod [92] PathEltOrInverse ::= PathElt '^' PathElt [93] PathMod ::= '?' '*' '+' [94] PathPrimary ::= iri 'a' '!' PathNegatedPropertySet '(' Path ')' [95] PathNegatedPropertySet ::= PathOneInPropertySet '(' PathOneInPropertySet '|' PathOneInPropertySet ')' [96] PathOneInPropertySet ::= iri 'a' '^' iri 'a' [97] Integer ::= INTEGER [98] TriplesNode ::= Collection BlankNodePropertyList [99] BlankNodePropertyList ::= '[' PropertyListNotEmpty ']' [100] TriplesNodePath ::= CollectionPath BlankNodePropertyListPath [101] BlankNodePropertyListPath ::= '[' PropertyListPathNotEmpty ']' [102] Collection ::= '(' GraphNode ')' [103] CollectionPath ::= '(' GraphNodePath ')' [104] GraphNode ::= VarOrTerm TriplesNode [105] GraphNodePath ::= VarOrTerm TriplesNodePath [106] VarOrTerm ::= Var GraphTerm [107] VarOrIri ::= Var iri [108] Var ::= VAR1 VAR2 [109] GraphTerm ::= iri RDFLiteral NumericLiteral BooleanLiteral BlankNode NIL [110] Expression ::= ConditionalOrExpression [111] ConditionalOrExpression ::= ConditionalAndExpression '||' ConditionalAndExpression [112] ConditionalAndExpression ::= ValueLogical '&&' ValueLogical [113] ValueLogical ::= RelationalExpression [114] RelationalExpression ::= NumericExpression '=' NumericExpression '!=' NumericExpression '<' NumericExpression '>' NumericExpression '<=' NumericExpression '>=' NumericExpression 'IN' ExpressionList 'NOT' 'IN' ExpressionList [115] NumericExpression ::= AdditiveExpression [116] AdditiveExpression ::= MultiplicativeExpression '+' MultiplicativeExpression '-' MultiplicativeExpression NumericLiteralPositive NumericLiteralNegative '*' UnaryExpression '/' UnaryExpression [117] MultiplicativeExpression ::= UnaryExpression '*' UnaryExpression '/' UnaryExpression [118] UnaryExpression ::= '!' PrimaryExpression '+' PrimaryExpression '-' PrimaryExpression PrimaryExpression [119] PrimaryExpression ::= BrackettedExpression BuiltInCall iriOrFunction RDFLiteral NumericLiteral BooleanLiteral Var [120] BrackettedExpression ::= '(' Expression ')' [121] BuiltInCall ::= Aggregate 'STR' '(' Expression ')' 'LANG' '(' Expression ')' 'LANGMATCHES' '(' Expression ',' Expression ')' 'DATATYPE' '(' Expression ')' 'BOUND' '(' Var ')' 'IRI' '(' Expression ')' 'URI' '(' Expression ')' 'BNODE' '(' Expression ')' NIL 'RAND' NIL 'ABS' '(' Expression ')' 'CEIL' '(' Expression ')' 'FLOOR' '(' Expression ')' 'ROUND' '(' Expression ')' 'CONCAT' ExpressionList SubstringExpression 'STRLEN' '(' Expression ')' StrReplaceExpression 'UCASE' '(' Expression ')' 'LCASE' '(' Expression ')' 'ENCODE_FOR_URI' '(' Expression ')' 'CONTAINS' '(' Expression ',' Expression ')' 'STRSTARTS' '(' Expression ',' Expression ')' 'STRENDS' '(' Expression ',' Expression ')' 'STRBEFORE' '(' Expression ',' Expression ')' 'STRAFTER' '(' Expression ',' Expression ')' 'YEAR' '(' Expression ')' 'MONTH' '(' Expression ')' 'DAY' '(' Expression ')' 'HOURS' '(' Expression ')' 'MINUTES' '(' Expression ')' 'SECONDS' '(' Expression ')' 'TIMEZONE' '(' Expression ')' 'TZ' '(' Expression ')' 'NOW' NIL 'UUID' NIL 'STRUUID' NIL 'MD5' '(' Expression ')' 'SHA1' '(' Expression ')' 'SHA256' '(' Expression ')' 'SHA384' '(' Expression ')' 'SHA512' '(' Expression ')' 'COALESCE' ExpressionList 'IF' '(' Expression ',' Expression ',' Expression ')' 'STRLANG' '(' Expression ',' Expression ')' 'STRDT' '(' Expression ',' Expression ')' 'sameTerm' '(' Expression ',' Expression ')' 'isIRI' '(' Expression ')' 'isURI' '(' Expression ')' 'isBLANK' '(' Expression ')' 'isLITERAL' '(' Expression ')' 'isNUMERIC' '(' Expression ')' RegexExpression ExistsFunc NotExistsFunc [122] RegexExpression ::= 'REGEX' '(' Expression ',' Expression ',' Expression ')' [123] SubstringExpression ::= 'SUBSTR' '(' Expression ',' Expression ',' Expression ')' [124] StrReplaceExpression ::= 'REPLACE' '(' Expression ',' Expression ',' Expression ',' Expression ')' [125] ExistsFunc ::= 'EXISTS' GroupGraphPattern [126] NotExistsFunc ::= 'NOT' 'EXISTS' GroupGraphPattern [127] Aggregate ::= 'COUNT' '(' 'DISTINCT' '*' Expression ')' 'SUM' '(' 'DISTINCT' Expression ')' 'MIN' '(' 'DISTINCT' Expression ')' 'MAX' '(' 'DISTINCT' Expression ')' 'AVG' '(' 'DISTINCT' Expression ')' 'SAMPLE' '(' 'DISTINCT' Expression ')' 'GROUP_CONCAT' '(' 'DISTINCT' Expression ';' 'SEPARATOR' '=' String ')' [128] iriOrFunction ::= iri ArgList [129] RDFLiteral ::= String LANGTAG '^^' iri [130] NumericLiteral ::= NumericLiteralUnsigned NumericLiteralPositive NumericLiteralNegative [131] NumericLiteralUnsigned ::= INTEGER DECIMAL DOUBLE [132] NumericLiteralPositive ::= INTEGER_POSITIVE DECIMAL_POSITIVE DOUBLE_POSITIVE [133] NumericLiteralNegative ::= INTEGER_NEGATIVE DECIMAL_NEGATIVE DOUBLE_NEGATIVE [134] BooleanLiteral ::= 'true' 'false' [135] String ::= STRING_LITERAL1 STRING_LITERAL2 STRING_LITERAL_LONG1 STRING_LITERAL_LONG2 [136] iri ::= IRIREF PrefixedName [137] PrefixedName ::= PNAME_LN PNAME_NS [138] BlankNode ::= BLANK_NODE_LABEL ANON Productions for terminals: [139] IRIREF ::= '<' ([^<>"{}|^`\]-[#x00-#x20])* '>' [140] PNAME_NS ::= PN_PREFIX [141] PNAME_LN ::= PNAME_NS PN_LOCAL [142] BLANK_NODE_LABEL ::= '_:' ( PN_CHARS_U PN_CHARS PN_CHARS [143] VAR1 ::= '?' VARNAME [144] VAR2 ::= '$' VARNAME [145] LANGTAG ::= '@' [a-zA-Z]+ ('-' [a-zA-Z0-9]+)* [146] INTEGER ::= [0-9]+ [147] DECIMAL ::= [0-9]* '.' [0-9]+ [148] DOUBLE ::= [0-9]+ '.' [0-9]* EXPONENT EXPONENT EXPONENT [149] INTEGER_POSITIVE ::= '+' INTEGER [150] DECIMAL_POSITIVE ::= '+' DECIMAL [151] DOUBLE_POSITIVE ::= '+' DOUBLE [152] INTEGER_NEGATIVE ::= '-' INTEGER [153] DECIMAL_NEGATIVE ::= '-' DECIMAL [154] DOUBLE_NEGATIVE ::= '-' DOUBLE [155] EXPONENT ::= [eE] [+-]? [0-9]+ [156] STRING_LITERAL1 ::= "'" ( ([^#x27#x5C#xA#xD]) | ECHAR [157] STRING_LITERAL2 ::= '"' ( ([^#x22#x5C#xA#xD]) | ECHAR [158] STRING_LITERAL_LONG1 ::= "'''" ( ( "'" | "''" )? ( [^'\] | ECHAR [159] STRING_LITERAL_LONG2 ::= '"""' ( ( '"' | '""' )? ( [^"\] | ECHAR [160] ECHAR ::= '\' [tbnrf\"'] [161] NIL ::= '(' WS [162] WS ::= #x20 | #x9 | #xD | #xA [163] ANON ::= '[' WS [164] PN_CHARS_BASE ::= [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] [165] PN_CHARS_U ::= PN_CHARS_BASE [166] VARNAME ::= ( PN_CHARS_U PN_CHARS_U [167] PN_CHARS ::= PN_CHARS_U [168] PN_PREFIX ::= PN_CHARS_BASE PN_CHARS PN_CHARS [169] PN_LOCAL ::= ( PN_CHARS_U PLX PN_CHARS PLX PN_CHARS PLX [170] PLX ::= PERCENT PN_LOCAL_ESC [171] PERCENT ::= '%' HEX HEX [172] HEX ::= [0-9] | [A-F] | [a-f] [173] PN_LOCAL_ESC ::= '\' ( '_' | '~' | '.' | '-' | '!' | '$' | '&' | "'" | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%' ) See Section 19 SPARQL Grammar SPARQL Query strings 16 Query Forms 22. Internet Media Type This specification is intended for use in conjunction with the SPARQL 1.1 Protocol [ SPROT SPARQL XML Results SPARQL-JSON-Results SPARQL CSV and TSV Results Note that the SPARQL protocol describes a means for conveying SPARQL queries to an SPARQL query processing service and returning the query results to the entity that requested them. 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 file: SPARQL requests may cause additional requests to be issued from the SPARQL endpoint, such as FROM NAMED. The endpoint is potentially within an organisations firewall or DMZ, and so such queries may be a source of indirection attacks. 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 Internationalized Resource Identifiers (IRIs) RFC3987 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" (lowercase) on all platforms. It is recommended that sparql query files stored on Macintosh HFS file systems be given a file type of "TEXT". 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 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 RFC 3629 RFC3629 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: [email protected] Intended usage: COMMON Restrictions on usage: None Author/Change controller: The SPARQL 1.1 specification is a work product of the World Wide Web Consortium's SPARQL Working Group. The W3C has change control over these specifications. [CHARMOD] Character Model for the World Wide Web 1.0: Fundamentals Latest version [CONCEPTS] Resource Description Framework (RDF): Concepts and Abstract Syntax Latest version [FUNCOP] XQuery 1.0 and XPath 2.0 Functions and Operators Latest version [RDF-MT] RDF Semantics Latest version [RFC3629] RFC 3629 UTF-8, a transformation format of ISO 10646 [RFC4647] RFC 4647 Matching of Language Tags [RFC3986] RFC 3986 Uniform Resource Identifier (URI): Generic Syntax [RFC3987] RFC 3987 Internationalized Resource Identifiers (IRIs) [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 Latest version [XPATH20] XML Path Language (XPath) 2.0 Latest version [XQUERY] XQuery 1.0: An XML Query Language Latest version [XSDT] XML Schema Part 2: Datatypes Second Edition Latest version W3C XML Schema Definition Language (XSD) 1.1 Part 2: Datatypes Latest version [BCP47] Best Common Practice 47 [CBD] CBD - Concise Bounded Description [DC] Expressing Simple Dublin Core in RDF/XML Dublin Core Dublin Core Metadata Initiative [Multiset] Multiset latest version [SPARQL XML Results] SPARQL Query Results XML Format (Second Edition) Latest version [SPARQL JSON Results] SPARQL 1.1 Query Results JSON Format Latest version [SPARQL CSV and TSV Result] SPARQL 1.1 Query Results CSV and TSV Formats Latest version [SPROT] SPARQL 1.1 Protocol Latest version [TURTLE] Turtle: Terse RDF Triple Language Latest version [UCNR] RDF Data Access Use Cases and Requirements Latest version [UCNR2] SPARQL New Features and Rationale Latest version [UNISEC] Unicode Security Considerations [VCARD] Representing vCard Objects in RDF/XML Latest version http://www.w3.org/TR/vcard-rdf [WEBARCH] Architecture of the World Wide Web, Volume One Latest version http://www.w3.org/TR/webarch/ [UNIID] Identifier and Pattern Syntax 4.1.0 Latest version http://www.unicode.org/reports/tr31/ Change Log Changes since Proposed Recommendation Fixed error in example of inverse property path Changes since Last Call The following are the corrections made since last publication: Grammar: DISTINCT Restore translation of BIND Since SPARQL 1.0 The new features in SPARQL 1.1 Query are: Aggregates Subqueries Negation Expressions in the SELECT clause Property Paths Assignment A short form for CONSTRUCT An expanded set of functions and operators