You are on page 1of 11

Appendix D: SPARQL

SPARQL is a recursive acronym for the SPARQL Protocol and RDF Query
Language. This appendix contains several examples of the SPARQL query
language and details, in alphabetical order, the operators and keywords that are part
of the SPARQL recommendation. In the case of keywords, we give a short
description. We list page numbers if a keyword or example is described in finer
detail in the book. Also, we provide a reference URL to additional information in the
W3C reference.

SPARQL Examples
The following examples can also be found in Chapter 6, "Discovering Information".

# George Washington's Namesakes


SELECT ?location
WHERE {
?person <http://www.w3.org/2000/01/rdf-
schema#labeliteral>
"George Washington"@en.
?location <http://dbpedia.org/property/namedFor> ?
person
}
# George Washington's Namesakes using prefixes
PREFIX rdfs: <http://www.w3.Org/2000/01/rdf-schema#>
PREFIX dbprop: <http://dbpedia.org/property/>
SELECT ?location
WHERE {
?person rdfs:label "George Washington"@en.
?location dbprop:namedFor ?person
}

# A sorted query for information on George Washington


PREFIX rdfs: <http://www.w3.Org/2000/01/rdf-schema#>
PREFIX dbprop: <http://dbpedia.org/property/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?job ?birthLoc ?picture
WHERE {
?person rdfs:label "George Washington"@en;
dbprop:occupation ?job;
dbprop:birthplace ?birthLoc;
foaf:img ?picture
} ORDER BY ?birthLoc DESC(?job)

# Information about Tim Berners-Lee's FOAF friends


PREFIX tbl: <http://www.w3.org/People/Berners-Lee/card#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX karl:
<http://www.w3.org/People/karl/karl-foaf.xrdf#>
SELECT ?personName2 ?predicate ?object
FROM <http://www.w3.org/People/Berners-Lee/card>
FROM <http://www.w3.org/People/karl/karl-foaf.xrdf>
FROM <http://www.koalie.net/foaf.rdf>
FROM <http://heddley.com/edd/foaf.rdf>
FROM <http://www.cs.umd.edu/~hendler/2003/foaf.rdf>
FROM <http://www.dajobe.org/foaf.rdf>
FROM <http: //www.isi.edu/~gil/foaf.rdf>
FROM <http://www.ivan-herman.net/foaf.rdf>
FROM <http://www.kjetil.kjernsmo.net/foaf>
FROM <http://www.lassila.org/ora.rdf>
FROM <http://www.mindswap.org/2004/owl/mindswappers>
WHERE {
tbl:i foaf:knows ?person.
?person foaf:name ?personName1;
rdfs:seeAlso ?iri.
?iri foaf:primaryTopic ?person2.
?person2 foaf:name ?personName2;
?predicate ?object
FILTER(?personNamel = ?personName2).
}
# Various names of Tim Berners-Lee's FOAF friends
# using named graphs
PREFIX tbl: <http://www.w3.org/People/Berners-Lee/card#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdfs: <http://www.w3.Org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.Org/1999/02/22-rdf-syntax-ns#>
SELECT *
FROM NAMED <http://www.koalie.net/foaf.rdf>
FROM NAMED <http://heddley.com/edd/foaf.rdf>
FROM NAMED <http://www.cs.umd.edu/~hendler/2003/foaf.rdf>
FROM NAMED <http://www.dajobe.org/foaf.rdf>
FROM NAMED <http://www.isi.edu/~gil/foaf.rdf>
FROM NAMED <http://www.ivan-herman.net/foaf.rdf>
FROM NAMED <http://www.kjetil.kjernsmo.net/foaf>
FROM NAMED <http://www.lassila.org/ora.rdf>
FROM NAMED
<http://www.mindswap.org/2004/owl/mindswappers>
WHERE {
GRAPH ?originGraph {
_:blank1 foaf:knows _:blank2.
_:blank2 rdf:type foaf:Person;
foaf:nick ?nickname;
foaf:name ?realname
}
}

# A filtered SPARQL query for any information regarding


# George Washington's last term as the President of the
# United States
PREFIX rdfs: <http://www.w3.Org/2000/01/rdf-schema#>
PREFIX dbprop: <http://dbpedia.org/property/>
PREFIX xsd: <http://www.w3.Org/2001/XMLSchema#>
SELECT ?prop ?object
WHERE {
?person rdfs:label "George Washington"@en;
dbprop:presidentstart ?start;
?prop ?object.
FILTER(xsd:integer(?start) + 4 <=
xsd:integer(?object))
}

# An optional SPARQL query that may return an image,


# mailbox or last name of any given set of FOAF friends
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT *
WHERE {
?person foaf:name ?name.
OPTIONAL {
?person foaf:img ?img;
foaf:mbox ?mbox;
foaf:family_name ?fName
}
}

# Returning FOAF information with a CONSTRUCT statement


PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rdf: <http://www.w3.Org/1999/02/22-rdf-syntax-ns#>
PREFIX ms: <http://www.mindswap.Org/2003/owl/mindswap#>
CONSTRUCT {
?person rdf:type foaf:Person;
foaf:name ?rname;
foaf:homepage ?hpage;
foaf:nick ?nick;
foaf:mbox ?mbox.
}
FROM NAMED <http://www.kjetil.kjernsmo.net/foaf>
FROM NAMED <http://www.dajobe.org/foaf.rdf>
FROM NAMED <http://heddley.com/edd/foaf.rdf>
FROM NAMED <http://www.cs.umd.edu/~hendler/2003/foaf.rdf>
FROM NAMED <http://www.koalie.net/foaf.rdf>
FROM NAMED <http://www.isi.edu/~gil/foaf.rdf>
FROM NAMED <http://www.ivan-herman.net/foaf.rdf>
FROM NAMED <http://www.lassila.org/ora.rdf>
FROM NAMED
<http://www.mindswap.org/2004/owl/mindswappers>
WHERE {
GRAPH ?originGraph {
# This pattern now returns information for everyone
# except www.mindswap.org.
{
_:blank1 foaf:knows ?person.
?person rdf:type foaf:Person.
# If we find a foaf:Person, then make sure we
# either the nickname and/or the name and/or the
# homepage. If we had omitted the FILTER clause,
# then we could have returned a query solution
# containing ?orginGraph and no other
# information!
OPTIONAL { ?person foaf:nick ?nick }.
OPTIONAL { ?person foaf:name ?rname }.
OPTIONAL { ?person foaf:homepage ?hpage }.
FILTER (bound(?nick) || bound(?rname) ||
bound(?hpage))
}
# Here's where we grab www.mindswap.org folks of
# all stripes. We are claiming that any friends we
# find will have triples declaring his/her name,
# homepage and mailbox.
UNION {
{ ?person rdf:type ms:Affiliate }
UNION
{ ?person rdf:type ms:Alumni }
UNION
{ ?person rdf:type ms:Faculty }
UNION
{ ?person rdf:type ms:Programmer }
UNION
{ ?person rdf:type ms:Researcher }
UNION
{ ?person rdf:type ms:GraduateStudent }
UNION
{ ?person rdf:type ms:UndergraduateStudent } .
?person foaf:name ?rname;
foaf:homepage ?hpage;
foaf:mbox ?mbox
}
}
}

# Using a DESCRIBE statement for George Washington


PREFIX rdf:
<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dbpedia: <http://dbpedia.org/resource/>
DESCRIBE *
WHERE {
?person ?anyProperty dbpedia:George_Washington
}

# An ASK SPARQL query determining whether George


# Washington was president in the year 1795
PREFIX rdfs: <http://www.w3.Org/2000/01/rdf-schema#>
PREFIX dbprop: <http://dbpedia.org/property/>
PREFIX xsd: <http://www.w3.Org/2001/XMLSchema#>
ASK
WHERE {
?person rdfs:label "George Washington"@en;
dbprop:presidentstart ?startDate;
dbprop:presidentEnd ?endDate.
FILTER(xsd:integer(?startDate) < xsd:integer('1795')
&&
xsd:integer(?endDate) > xsd:integer('1795'))
}

Operators
This section contains a list of all supported SPARQL query language operators as documented in the
W3C SPARQL Recommendation (http://www.w3.org/TR/rdf-sparql-query/#OperatorMapping). To
avoid duplication, some operators are specified here while others are discussed in the "Keywords"
section. We provide short examples of each operator.

Unary Operators

Unary operators are those operations that require only a single argument.
 !boolExpr Returns true if boolExpr is false and returns false if boolExpr is true.
!(true) will return false.
 +numericExpression Returns the positive value of numericExpression.

 xsd:integer(?startDate) < +xsd:integer('1795')
 -numericExpression Returns the negative value of numericExpression.

 xsd:integer(?startDate) > -xsd:integer('1795')
 BOUND (?variable) Detailed in the "Keywords" section.

 BOUND(?x)
 DATATYPE(iri) Detailed in the "Keywords" section.

 FILTER)DATATYPE(?startDate) = xsd:integer)
 isBLANK(iri) Returns true if iri is a blank node; otherwise false.

 isBLANK(?x)
 isLITERAL(lit) Returns true if lit is an RDF literal; otherwise false.

 isLITERAL(?x)
 isIRI(iri) Detailed in the "Keywords" section.

 isIRI(?x)
 isURI(iri) Detailed in the "Keywords" section.

 isURI(?x)
 LANG(iri) Detailed in the "Keywords" section.

 LANG(?x)
 STR(iri) Detailed in the "Keywords" section.

 STR(?x)

Binary Operators

Binary operators are those operations that require two arguments. Any reference to types is specific
to XML Schema datatypes.
 boolExprl || boolExpr2 Returns true if either boolExpr1 or boolExpr2 is true; otherwise it
returns false.

 FILTER(?x > 0 || ?y = 1)
 boolExpr1 && boolExpr2 Returns true if both boolExpr1 or boolExpr2 are true; otherwise it
returns false.

 FILTER (?x > =0 && ?y = 1)
 expr1 = expr2 Returns true if expr1 and expr2 are equal in value; otherwise it
returns false, expr1 and expr2 can be of numeric, literal, boolean, string, or dateTime types
as well as RDF terms.

 FILTER(?x = ?y)
 expr1 != expr2 Returns true if expr1 and expr2 are not equal in value; otherwise it
returns false, expr1 and expr2 can be of numeric, literal, boolean, string, or dateTime
types as well as RDF terms.

 FILTER(?x != ?y)
 expr1 < expr2 Returns true if expr1 is less than expr2 in value; otherwise it
returns false, expr1 and expr2 can be of numeric, literal, boolean, string, or dateTime types.

 FILTER(?x < ?y)
 expr1 > expr2 Returns true if expr1 is greater than expr2 in value; otherwise it
returns false, expr1 and expr2 can be of numeric, literal, boolean, string, or dateTime
types.

 FILTER(?x > ?y)
 exprl >= expr2 Returns true if expr1 is less than or equal to expr2 in value; otherwise it
returns false, expr1 and expr2 can be of numeric, literal, boolean, string, or dateTime
types.

 FILTER(?x <= ?y)
 exprl >= expr2 Returns true if expr1 is greater than or equal to expr2 in value; otherwise it
returns false, expr1 and expr2 can be of numeric, literal, boolean, string, or dateTime
types.

 FILTER(?x >= ?y)
 numericExpr1* numericExpr2 Returns the product of numericExpr1 and numericExpr2.

 FILTER(?x > ?y*5)
 numericExpr1* numericExpr2 Returns the quotient of
dividing numericExpr1 by numericExpr2.

 FILTER)?x > ?y/5)
 numericExpr1 + numericExpr2 Returns the sum of numericExpr1 and numericExpr2.

 FILTER)?x > ?y+5)
 numericExpr1 - numericExpr2 Returns the difference
between numericExpr1and numericExpr2.

 FILTER)?x > ?y-5)
 langMATCHES(iri1, iri2) Detailed in the "Keywords" section.

 langMATCHES(?x, "en")
 sameTERM(iri1, iri2) Detailed in the "Keywords" section.

 sameTERM(?x, ?y)
 REGEX(string, pattern) Returns true if pattern is found in string; otherwise false. Both
arguments must be simple literals.

 REGEX(?input, "John")

Trinary Operators

Trinary (aka ternary) operators are those operations that require three arguments.
 REGEX(string, pattern, flags) Returns true if pattern is found in string as dictated by the
flags argument; otherwise false. Both arguments must be simple literals. Flags, described in
detail at http://www.w3.org/TR/xpath-functions/#flags, is an xsd: string of any of the following
concatenated character arguments:
o i If present, then match pattern against string in a case-insensitive manner.
o m If present, then match pattern against string where string supports multiple lines.
This affects how characters ^, $, and newline characters are interpreted.
o s If present, then match pattern against string where string supports single lines.
o x If present, then remove all whitespaces in pattern before matching. The sole
exception is against any whitespaces present in a character class exception (i.e.,
those delimited with a set of square brackets).
o
o REGEX(?input, "John", "is")

Keywords
The SPARQL Recommendation notes the set of keywords that are part of the query language. They
are listed here in alphabetical order along with a description of each. Note that there is some overlap
with some of the operators described in the previous section (for example, regex, sameTERM), but
they are listed here for completeness as part of the Recommendation's Extended Backus-Naur Form
(EBNF).
 a A shortcut keyword that can be used in place of the predicate
IRI http://www.w3.org/1999/02/22-rdf-syntax-ns#type. Described
at http://www.w3.org/TR/rdf-sparql-query/#abbrevRdfType.
 ASK A SPARQL query form that tests whether or not a query has a matching graph pattern or
not. Described on page 225 as well as http://www.w3.org/TR/rdf-sparql-query/#ask.
 BASE Defines a base IRI that resolves relative IRIs. Described on page 224 as
wellas http://www.w3.org/TR/rdf-sparql-query/#relIRIs.
 BOUND Returns true if the given variable is bound to a value, or else it returns false.
Variables with values of NAN (not a number) or INF (infinity) are considered not bound.
Described on page 220 as well as http://www.w3.org/TR/rdf-sparql-query/#func-bound.
 CONSTRUCT A SPARQL query form that returns a single RDF graph as specified by the query's
graph template. Described on page 222 as well as http://www.w3.org/TR/rdf-sparql-
query/#construct.
 DATATYPE This keyword returns the datatype of a given literal. Simple literals will always
return xsd:string. Described at http://www.w3.org/TR/rdf-sparql-query/#func-datatype.
 DESCRIBE A SPARQL query form that returns a single RDF graph for a set of RDF resources.
Described on page 224 as well as http://www.w3.org/TR/rdf-sparql-query/#describe.
 DISTINCT This keyword guarantees that duplicate query results that are bound to identical
variables are removed. Described at http://www.w3.org/TR/rdf-sparql-query/#modDistinct.
 false A keyword that is shorthand for the literal “false”^^xsd: boolean.Described
at http://www.w3.org/TR/rdf-sparql-query/#QSynLiterals.
 FILTER Restricts the number of solutions in a result set based on a given expression.
Described on page 213 as well as http://www.w3.org/TR/rdf-sparql-query/#tests.
 FROM Specifies a default RDF dataset against which a query is performed. The dataset is
identified by an IRI. Described on page 202 as well as http://www.w3.org/TR/rdf-sparql-
query/#specifyingDataset.
 FROM NAMED Specifies a named RDF dataset against which a query is performed. The
dataset is identified by an IRI. Described on page 202 as well as http://www.w3.org/TR/rdf-
sparql-query/#specifyingDataset.
 GRAPH Used in conjunction with named graphs, graph specifies both a variable and a graph
pattern. The variable specifies the named graph against which the graph pattern is
executed. Described on page 206 as well as http://www.w3.org/TR/rdf-sparql-
query/#queryDataset.
 isIRI A SPARQL operator that returns true if the given value is an IRI or falseOtherwise.
Described at http://www.w3.org/TR/rdf-sparql-query/#func-isIRI.
 isLITERAL A SPARQL operator that returns true if the given value is an RDF literal
or false otherwise. Described at http://www.w3.org/TR/rdf-sparql-query#func-isLiteral.
 isURI Identical in functionality to isiRi, isURi returns true if the given value is an IRI
or false otherwise. Described at http://www.w3.org/TR/rdf-sparql-query/#func-isIRI.
 LANG This keyword returns the language tag of a given literal; otherwise it returns an empty
string. Described at http://www.w3.org/TR/rdf-sparql-query/#func-lang.
 LANGMATCHES A SPARQL operator that takes two arguments. LANGMATCHESreturns true if the
first argument is a member of the language tags passed in the second argument.
Otherwise, it returns false. Described athttp://www.w3.org/TR/rdf-sparql-query/#func-
langMatches.
 LIMIT Places an upper bound on the number of results returned in a result set. Described
on page 211 as well as http://www.w3.org/TR/rdf-sparql-query/#modResultLimit.
 OFFSET This keyword causes the solutions generated in a result set to begin after a given
number of solutions. Described on page 211 as well as http://www.w3.org/TR/rdf-sparql-
query/#modOffset.
 OPTIONAL Notes that certain portions of a graph pattern are not required as part of a query
but should be included if there is a match. Described on page 215as well
as http://www.w3.org/TR/rdf-sparqi-query/#OptionalMatching.
 ORDER BY This keyword enables solutions in a result set to be arranged by one or more
variables in either an ascending or descending order. Described on page 210 as well
as http://www.w3.org/TR/rdf-sparql-query/#modOrderBy.
 PREFIX Allows a prefix label to be associated with a given IRI. Described on page 197 as well
as http://www.w3.org/TR/rdf-sparql-query/#prefNames.
 REDUCED A weaker version of DISTINCT, this keyword signals the SPARQL endpoint to
optionally remove duplicate solutions. Described on page 210 as well
as http://www.w3.org/TR/rdf-sparql-query/imodReduced.
 REGEX Specifies that the XPath function fn:matches should be used to match a given pattern
against a given text string. Optional flags are also available. Described on page 215 as
well as http://www.w3.org/TR/rdf-sparql-query/#funcex-regex.
 sameTERM This keyword returns true if the two given arguments are equal RDF terms.
Otherwise it returns false. Described at http://www.w3.org/TR/rdf-sparql-query/#func-
sameTerm.
 SELECT A SPARQL query form that returns a set of variables and their bindings in an XML
result set. Described on page 197 as well as http://www.w3.org/TR/rdf-sparql-
query/#select.
 STR A SPARQL operator that returns the string representation of a given literal or IRI.
Described at http://www.w3.org/TR/rdf-sparql-query/#func-str.
 true A keyword that is shorthand for the literal “true”^^ xsd:boolean. Described
at http://www.w3.org/TR/rdf-sparql-query/#QSynLiterals.
 UNION Allows for the result sets of two or more graph patterns to be combined into a single
result. Described on page 219 as well as http://www.w3.org/TR/rdf-sparql-
query/#alternatives.
 WHERE This keyword precedes a graph pattern that is used to match RDF data against some
set of RDF datasets. Described on page 193 as well as http://www.w3.org/TR/rdf-sparql-
query/#GraphPattern.

You might also like