Chapter 6. The SeRQL query language (revision 1.2)

Table of Contents

6.1. Revisions
6.1.1. revision 1.1
6.1.2. revision 1.2
6.2. Introduction
6.3. URIs, literals and variables
6.3.1. Variables
6.3.2. URIs
6.3.3. Literals
6.3.4. Blank Nodes (R1.2)
6.4. Path expressions
6.4.1. Basic path expressions
6.4.2. Path expression short cuts
6.4.3. Optional path expressions
6.5. Select- and construct queries
6.6. Select queries
6.7. Construct queries
6.8. The WHERE clause
6.8.1. Boolean constants
6.8.2. Value (in)equality
6.8.3. Numerical comparisons
6.8.4. The LIKE operator (R1.2)
6.8.5. isResource() and isLiteral()
6.8.6. isURI() and isBNode() (R1.2)
6.8.7. AND, OR, NOT
6.8.8. Nested WHERE clauses (R1.2)
6.9. Other functions
6.9.1. label(), lang() and datatype()
6.9.2. namespace() and localName() (R1.2)
6.10. The LIMIT and OFFSET clauses
6.11. The USING NAMESPACE clause
6.12. Built-in predicates
6.13. Set combinatory operations
6.13.1. UNION (R1.2)
6.13.2. INTERSECT (R1.2)
6.13.3. MINUS (R1.2)
6.14. NULL values
6.15. Query Nesting
6.15.1. The IN operator (R1.2)
6.15.2. ANY and ALL (R1.2)
6.15.3. EXISTS (R1.2)
6.16. Example SeRQL queries
6.16.1. Query 1
6.16.2. Query 2
6.16.3. Query 3
6.17. Comments/feedback
6.18. References
6.19. SeRQL grammar

6.1. Revisions

6.1.1. revision 1.1

SeRQL revision 1.1 is a syntax revision (see issue tracker item SES-75). This document describes the revised syntax. From Sesame release 1.2-RC1 onwards, the old syntax is no longer supported.

6.1.2. revision 1.2

SeRQL revision 1.2 covers a set of new functions and operators:

New operations have been marked with (R1.2) where appropriate in this document.

6.2. Introduction

SeRQL ("Sesame RDF Query Language", pronounced "circle") is a new RDF/RDFS query language that is currently being developed by Aduna as part of Sesame. It combines the best features of other (query) languages (RQL, RDQL, N-Triples, N3) and adds some of its own. This document briefly shows all of these features. After reading through this document one should be able to write SeRQL queries.

Some of SeRQL's most important features are:

  • Graph transformation.
  • RDF Schema support.
  • XML Schema datatype support.
  • Expressive path expression syntax.
  • Optional path matching.

6.3. URIs, literals and variables

URIs and literals are the basic building blocks of RDF. For a query language like SeRQL, variables are added to this list. The following sections will show how to write these down in SeRQL.

6.3.1. Variables

Variables are identified by names. These names must start with a letter or an underscore ('_') and can be followed by zero or more letters, numbers, underscores, dashes ('-') or dots ('.'). Examples variable names are:

  • Var1
  • _var2
  • unwise.var-name_isnt-it

SeRQL keywords are not allowed to be used as variable names. Currently, the following keywords are used or reserved for future use in SeRQL: select, construct, from, where, using, namespace, true, false, not, and, or, like, label, lang, datatype, null, isresource, isliteral, sort, in, union, intersect, minus, exists, forall, distinct, limit, offset.

Keywords in SeRQL are all case-insensitive, this in contrast to variable names; these are case-sensitive.

6.3.2. URIs

There are two ways to write down URIs in SeRQL: either as full URIs or as abbreviated URIs. Full URIs must be surrounded with "<" and ">". Examples of this are:

  • <http://www.openrdf.org/index.html>
  • <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
  • <mailto:sesame@openrdf.org>
  • <file:///C:\rdffiles\test.rdf>

As URIs tend to be long strings with the first part being shared by several of them (i.e. the namespace), SeRQL allows one to use abbreviated URIs (or QNames) by defining (short) names for these namespaces which are called "prefixes". A QName always starts with one of the defined prefixes and a colon (":"). After this colon, the part of the URI that is not part of the namespace follows. The first part, consisting of the prefix and the colon, is replaced by the full namespace by the query engine. Some example QNames are:

  • sesame:index.html
  • rdf:type
  • foaf:Person

6.3.3. Literals

RDF literals consist of three parts: a label, a language tag, and a datatype. The language tag and the datatype are optional and at most one of these two can accompany a label (a literal can not have both a language tag and a datatype). The notation of literals in SeRQL has been modelled after their notation in N-Triples; literals start with the label, which is surrounded by double quotes, optionally followed by a language tag with a "@" prefix or by a datatype URI with a "^^" prefix. Example literals are:

  • "foo"
  • "foo"@en
  • "<foo/>"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral>

The SeRQL notation for abbreviated URIs can also be used. When the prefix rdf is mapped to the namespace http://www.w3.org/1999/02/22-rdf-syntax-ns#, the last example literal could also have been written down like:

  • "<foo/>"^^rdf:XMLLiteral

SeRQL has also adopted the character escapes from N-Triples; special characters can be escaped by prefixing them with a backslash. One of the special characters is the double quote. Normally, a double quote would signal the end of a literal's label. If the double quote is part of the label, it needs to be escaped. For example, the sentence John said: "Hi!" can be encoded in a SeRQL literals as: "John said: \"Hi!\"".

As the backslash is a special character itself, it also needs to be escaped. To encode a single backslash in a literal's label, two backslashes need to be written in the label. For example, a Windows directory would be encoded as: "C:\\Program Files\\Apache Tomcat\\".

SeRQL has functions for extracting each of the three parts of a literal. These functions are label, lang, and datatype. label("foo"@en) extracts the label "foo", lang("foo"@en) extracts the language tag "en", and datatype("foo"^^rdf:XMLLiteral) extracts the datatype rdf:XMLLiteral. The use of these functions is explained later.

6.3.4. Blank Nodes (R1.2)

RDF has a notion of blank nodes. These are nodes in the RDF graph that are not labeled with a URI or a literal. The interpretation of such blank nodes is as a form of existential quantification: it allows one to assert that "there exists a node such that..." without specifying what that particular node is. Blank nodes do in fact often have identifiers, but these identifiers are assigned internally by whatever processor is processing the graph and they are only valid in the local context, not as global identifiers (unlike URIs).

Strictly speaking blank nodes are only addressable indirectly, by querying for one or more properties of the node. However, SeRQL, as a practical shortcut, allows blank node identifiers to be used in queries. The syntax for blank nodes is adopted from N-Triples, using a QName-like syntax with "_" as the namespace prefix, and the internal blank node identifier as the local name. For example:

  • _:bnode1

This identifies the blank node with internal identifier "bnode1". These blank node identifiers can be used in the same way that normal URIs or QNames can be used.

Caution: It is important to realize that addressing blank nodes in this way makes SeRQL queries non-portable across repositories. There is no guarantee that in two repositories, even if they contain identical datasets, the blank node identifiers will be identical. It may well be that "bnode1" in repository A is a completely different blank node than "bnode1" in repository B. Even in the same repository, it is not guaranteed that blank node identifiers are stable over updates: if certain statements are added to or removed from a repository, it is not guaranteed "bnode1" still identifies the same blank node that it did before the update operation.

6.4. Path expressions

One of the most prominent parts of SeRQL are path expressions. Path expressions are expressions that match specific paths through an RDF graph. Most current RDF query languages allow you to define path expressions of length 1, which can be used to find (combinations of) triples in an RDF graph. SeRQL, like RQL, allows you to define path expressions of arbitrary length.

6.4.1. Basic path expressions

Imagine that we want to query an RDF graph for persons who work for companies that are IT companies. Querying for this information comes down to finding the following pattern in the RDF graph (gray nodes denote variables):

Figure 6.1. A basic path expression

A basic path expression

The SeRQL notation for path expressions resembles the picture above; it is written down as:

{Person} ex:worksFor {Company} rdf:type {ex:ITCompany}

The parts surrounded by curly brackets represent the nodes in the RDF graph, the parts between these nodes represent the edges in the graph. The direction of the arcs (properties) in SeRQL path expressions is always from left to right.

In SeRQL queries, multiple path expressions can be specified by seperating them with commas. For example, the path expression show before can also be written down as two smaller path expressions:

{Person} ex:worksFor {Company},
{Company} rdf:type {ex:ITCompany}

The nodes and edges in the path expressions can be variables, URIs and literals. Also, a node can be left empty in case one is not interested in the value of that node. Here are some more example path expressions to illustrate this:

  • {Person} ex:worksFor {} rdf:type {ex:ITCompany}
  • {Painting} ex:painted_by {} ex:name {"Picasso"}
  • {comic:RoadRunner} SomeRelation {foo:WillyECoyote}

6.4.2. Path expression short cuts

Each and every path can be constructed using a set of basic path expressions. Sometimes, however, it is nicer to use one of the available short cuts. There are three types of short cuts, all of them are explained below.

6.4.2.1. Multi-value nodes

In situations where one wants to query for two or more triples with identical subject and predicate, the subject and predicate do not have to be repeated over and over again. Instead, a multi-value node can be used:

{subj1} pred1 {obj1, obj2, obj3}

A built-in constraint on this construction is that each value for the variables in the multi-value node is unique (i.e. they are pairwise disjoint). Therefore, this path expression is equivalent to the following combination of path expressions and boolean constraints:

FROM
  {subj1} pred1 {obj1},
  {subj1} pred1 {obj2},
  {subj1} pred1 {obj3}
WHERE obj1 != obj2 AND obj1 != obj3 AND obj2 != obj3

Or graphically:

Figure 6.2. Multi-value nodes

Multi-value nodes

Multi-value nodes can also be used when statements share the predicate and object, e.g.:

{subj1, subj2, subj3} pred1 {obj1}

When used in a longer path expression, multi-value nodes apply to both the part left of the node and the part right of the node. The following path expression:

{first} pred1 {middle1, middle2} pred2 {last}

matches the following graph:

Figure 6.3. Multi-value nodes in a longer path expression

Multi-value nodes in a longer path expression

When using variables in multi-value nodes, a constraint on its values is implicitly added: the variable's value is not allowed to be equal to any other value in the multi-value node. So, in the first example, the variables obj1, obj2 and obj3 will not match identical values at the same time. This prevents the path from matching a single triple three times.

6.4.2.2. Branches

One of the shorts cuts that is likely going to be used most, is the notation for branches in path expressions. There are lots of situations where one wants to query multiple properties of a single subject. Instead of repeating the subject over and over again, one can use a semi-colon to attach a predicate-object combination to the subject of the last part of a path expression, e.g.:

{subj1} pred1 {obj1};
        pred2 {obj2}

Which is equivalent to:

{subj1} pred1 {obj1},
{subj1} pred2 {obj2}

Or graphically:

Figure 6.4. Branches in a path expression

Branches in a path expression

Or a slightly more complicated example:

{first} pred {} pred1 {obj1};
                pred2 {obj2} pred3 {obj3}

Which matches the following graph:

Figure 6.5. Branches in a longer path expression

Branches in a longer path expression

Note that an anonymous variable is used in the middle of the path expressions.

6.4.2.3. Reified statements

The last short cut is a short cut for reified statements. A path expression representing a single statement (i.e. {node} edge {node}) can be written between the curly brackets of a node, e.g.:

{ {reifSubj} reifPred {reifObj} } pred {obj}

This would be equivalent to querying (using "rdf:" as a prefix for the RDF namespace, and "_Statement" as a variable for storing the statement's URI):

{_Statement} rdf:type {rdf:Statement},
{_Statement} rdf:subject {reifSubj},
{_Statement} rdf:predicate {reifPred},
{_Statement} rdf:object {reifObj},
{_Statement} pred {obj}

Again, graphically:

Figure 6.6. A reification path expression

A reification path expression

6.4.3. Optional path expressions

Optional path expressions differ from 'normal' path expressions in that they do not have to be matched to find query results. The SeRQL query engine will try to find paths in the RDF graph matching the path expression, but when it cannot find any paths it will skip the expression and leave any variables in it uninstantiated (they will have the value null).

Consider an RDF graph that contains information about people that have names, ages, and optionally e-mail addresses. This is a situation that is likely to be very common in RDF data. A logical query on this data is a query that yields all names, ages and, when available, e-mail addresses of people, e.g.:

{Person} ex:name {Name};
         ex:age  {Age};
         ex:email {EmailAddress}

However, using normal path expressions like in the query above, people without e-mail address will not be returned by the SeRQL query engine. With optional path expressions, one can indicate that a specific (part of a) path expression is optional. This is done using square brackets, i.e.:

{Person} ex:name {Name};
         ex:age  {Age};
        [ex:email {EmailAddress}]

Or alternatively:

 {Person} ex:name {Name};
          ex:age  {Age},
[{Person} ex:email {EmailAddress}]

In contrast to the first path expressions, this expression will also match with people without an e-mail address. For these people, the variable EmailAddress will not be assigned a value.

Optional path expressions can also be nested. This is useful in situations where the existence of a specific path is dependent on the existence of another path. For example, the following path expression queries for the titles of all known documents and, if the author of the document is known, the name of the author (if it is known) and his e-mail address (if it is known):

{Document} ex:title {Title};
          [ex:author {Author} [ex:name {Name}];
                              [ex:email {Email}]]

With this path expression, the SeRQL query engine will not try to find the name and e-mail address of an author when it cannot even find the resource representing the author.

6.5. Select- and construct queries

The SeRQL query language supports two querying concepts. The first one can be characterized as returning a table of values, or a set of variable-value bindings. The second one returns a true RDF graph, which can be a subgraph of the graph being queried, or a graph containing information that is derived from it. The first type of queries are called "select queries", the second type of queries are called "construct queries".

A SeRQL query is typically built up from one to six clauses. For select queries these clauses are: SELECT, FROM, WHERE, LIMIT, OFFSET and USING NAMESPACE. One might recognize the first five clauses from SQL, but their usage is slightly different. For construct queries the clauses are the same with the exception of the first; construct queries start with a CONSTRUCT clause instead of a SELECT clause.

The first clause (i.e. SELECT or CONSTRUCT) determines what is done with the results that are found. In a SELECT clause, one can specify which variable values should be returned and in what order. In a CONSTRUCT clause, one can specify which triples should be returned.

The FROM clause is optional and always contains path expressions, which were explained in the previous section. It defines the paths in an RDF graph that are relevant to the query. Note that when the FROM clause is not specified, the query will simply return the constants specified in the SELECT or CONSTRUCT clause.

The WHERE clause is optional and can contain additional (Boolean) constraints on the values in the path expressions. These are constraints on the nodes and edges of the paths, which cannot be expressed in the path expressions themselves.

The LIMIT and OFFSET clauses are also optional. These clauses can be used separately or combined in order to get a subset of all query answers. Their usage is very similar to the LIMIT and OFFSET clauses in SQL queries. The LIMIT clause determines the (maximum) amount of query answers that will be returned. The OFFSET clause determines which query answer will be returned as the first result, skipping as many query results as specified in this clause.

Finally, the USING NAMESPACE clause is also optional and it can contain namespace declarations; these are the mappings from prefixes to namespaces that were referred to in one of previous sections about (abbreviated) URIs.

The WHERE, LIMIT, OFFSET and USING NAMESPACE clauses will be explained in one of the next sections. The following section will explain the SELECT and FROM clause.

6.6. Select queries

As said before, select queries return tables of values, or sets of variable-value bindings. Which values are returned can be specified in the select clause. One can specify variables and/or values in the select clause, seperated by commas. The following example query returns all URIs of classes:

SELECT C
FROM {C} rdf:type {rdfs:Class}

It is also possible to use a '*' in the SELECT clause. In that case, all variable values will be returned in the order in which they appear in the query, e.g.:

SELECT *
FROM {S} rdfs:label {O}

This query will return the values of the variables S and O, in that order. If a different order is preferred, one needs to specify the variables in the select clause, e.g.:

SELECT O, S
FROM {S} rdfs:label {O}

By default, the results of a select query are not filtered for duplicate rows. Because of the nature of the above queries, these queries will never return duplicates. However, more complex queries might result in duplicate result rows. These duplicates can be filtered out by the SeRQL query engine. To enable this functionality, one needs to specify the DISTINCT keyword after the select keyword. For example:

SELECT DISTINCT *
FROM {Country1} ex:borders {} ex:borders {Country2}
USING NAMESPACE
    ex = <http://example.org/things#>

6.7. Construct queries

Construct queries return RDF graphs as set of triples. The triples that a query should return can be specified in the construct clause using the previously explained path expressions. The following is an example construct query:

CONSTRUCT {Parent} ex:hasChild {Child}
FROM {Child} ex:hasParent {Parent}
USING NAMESPACE
    ex = <http://example.org/things#>

This query defines the inverse of the property foo:hasParent to be foo:hasChild. This is just one example of a query that produces information that is derived from the original information. Here is one more example:

CONSTRUCT
    {Artist} rdf:type {ex:Painter};
             ex:hasPainted {Painting}
FROM
    {Artist} rdf:type {ex:Artist};
             ex:hasCreated {Painting} rdf:type {ex:Painting}
USING NAMESPACE
    ex = <http://example.org/things#>

This query derives that an artist who has created a painting, is a painter. The relation between the painter and the painting is modelled to be art:hasPainted.

Instead of specifying a path expression in the CONSTRUCT clause, one can also use a '*'. In that case, the CONSTRUCT clause is identical to the FROM clause. This allows one to extract a subgraph from a larger graph, e.g.:

CONSTRUCT *
FROM {SUB} rdfs:subClassOf {SUPER}

This query extracts all rdfs:subClassOf relations from an RDF graph.

Just like with select queries, the results of a construct query are not filtered for duplicate triples by default. Again, these duplicates are filtered out by the SeRQL query engine if the DISTINCT keyword is specified after the construct keyword, for example:

CONSTRUCT DISTINCT
    {Artist} rdf:type {ex:Painter}
FROM
    {Artist} rdf:type {ex:Artist};
             ex:hasCreated {} rdf:type {ex:Painting}
USING NAMESPACE
    ex = <http://example.org/things#>

6.8. The WHERE clause

The third clause in a query is the WHERE clause. This is an optional clause in which one can specify Boolean constraints on variables.

The following sections will explain the available Boolean expressions for use in the WHERE clause. Section 6.8.8, “Nested WHERE clauses (R1.2)” will explain how WHERE clauses can be nested inside optional path expressions.

6.8.1. Boolean constants

There are two Boolean constants, TRUE and FALSE. The first one is simply always true, the last one is always false. The following query will never produce any results because the constraint in the where clause will never evaluate to true:

SELECT *
FROM {X} Y {Z}
WHERE FALSE

6.8.2. Value (in)equality

The most common boolean constraint is equality or inequality of values. Values can be compared using the operators "=" (equality) and "!=" (inequality). The expression

Var = <foo:bar>

is true if the variable Var contains the URI <foo:bar>, and the expression

Var1 != Var2

checks whether two variables are not equal.

6.8.3. Numerical comparisons

Numbers can be compared to each other using the operators "<" (lower than), "<=" (lower than or equal to), ">" (greater than) and ">=" (greater than or equal to). SeRQL uses a literal's datatype to determine whether its value is numerical. All XML Schema built-in numerical datatypes are supported, i.e.: xsd:float, xsd:double, xsd:decimal and all subtypes of xsd:decimal (xsd:long, xsd:nonPositiveInteger, xsd:byte, etc.), where the prefix xsd is used to reference the XML Schema namespace.

In the following query, a comparison between values of type xsd:positiveInteger is used to retrieve all countries that have a population of less than 1 million:

SELECT Country
FROM {Country} ex:population {Population}
WHERE Population < "1000000"^^xsd:positiveInteger
USING NAMESPACE
    ex = <http://example.org/things#>

SeRQL is currently restricted to numerical comparisons between values with identical datatypes. This means that e.g. xsd:int values cannot (yet) be compared to xsd:byte values.

If only one of the parameters of a comparison has a datatype, SeRQL will try to assign the other parameter the same datatype. This means that the above query can still be used when the population literals don't have any datatype. SeRQL will try to interpret the literal as a positive integer and compare it to the one million constant.

6.8.4. The LIKE operator (R1.2)

The LIKE operator can check whether a value matches a specified pattern of characters. '*' characters can be used as wildcards, matching with zero or more characters. The rest of the characters are compared lexically. The pattern is surrounded with double quotes, just like a literal's label.

SELECT Country
FROM {Country} ex:name {Name}
WHERE Name LIKE "Belgium"
USING NAMESPACE
    ex = <http://example.org/things#>

By default, the LIKE operator does a case-sensitive comparison: in the above query, the operator fails is the variable Name is bound to the value "belgium" instead of "Belgium". Optionally, one can specify that the operator should perform a case-insensitive comparison:

SELECT Country
FROM {Country} ex:name {Name}
WHERE Name LIKE "belgium" IGNORE CASE
USING NAMESPACE
    ex = <http://example.org/things#>

In this query, the operator will succeed for "Belgium", "belgium", "BELGIUM", etc.

The '*' character can be used as a wildcard to indicate substring matches, for example:

SELECT Country
FROM {Country} ex:name {Name}
WHERE Name LIKE "*Netherlands"
USING NAMESPACE
    ex = <http://example.org/things#>

This query will match any country names that end with the string "Netherlands", for example "The Netherlands".

6.8.5. isResource() and isLiteral()

The isResource() and isLiteral() boolean functions check whether a variable contains a resource or a literal, respectively. For example:

SELECT *
FROM {R} rdfs:label {L}
WHERE isLiteral(L)

6.8.6. isURI() and isBNode() (R1.2)

The isURI() and isBNode() boolean functions are more specific versions of isResource(). They check whether a variable is bound to a URI value or a BNode value, respectively. For example, the following query returns only URIs (and filters out all bNodes and literals):

SELECT V
FROM {R} prop {V}
WHERE isURI(V)

6.8.7. AND, OR, NOT

Boolean constraints and functions can be combined using the AND and OR operators, and negated using the NOT operator. The NOT operator has the highest presedence, then the AND operator, and finally the OR operator. Parentheses can be used to override the default presedence of these operators. The following query is a (kind of artifical) example of this:

SELECT *
FROM {X} Prop {Y} rdfs:label {L}
WHERE NOT L LIKE "*FooBar*" AND
      (Y = <foo:bar> OR Y = <bar:foo>) AND
      isLiteral(L)

6.8.8. Nested WHERE clauses (R1.2)

In order to be able to express boolean constraints on variables in optional path expressions, it is possible to use a nested WHERE clause. The constraints in such a nested WHERE clause restrict the potential matches of the optional path expressions, without causing the entire query to fail if the boolean constraint fails.

To illustrate the difference between a nested WHERE clause and a 'normal' WHERE clause, consider the following two queries on the same data:

Data (using Turtle format):

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

_:a  foaf:name   "Michael" .

_:b  foaf:name   "Rubens" .
_:b  ex:email    "rubinho@example.work".

_:b  foaf:name   "Giancarlo" .
_:b  ex:email    "giancarlo@example.work".
	

Query 1 (normal WHERE-clause):

SELECT 
   Name, EmailAddress
FROM
  {Person} foaf:name {Name};
          [ex:email {EmailAddress}]
WHERE EmailAddress LIKE "g*"
	

Query 2 (nested WHERE-clause):

SELECT 
   Name, EmailAddress
FROM
  {Person} foaf:name {Name};
          [ex:email {EmailAddress} WHERE EmailAddress LIKE "g*"]
	

In query 1, a normal WHERE clause specifies that the EmailAddress found by the optional expression must begin with the letter "g". The result of this query will be:

NameEmailAddress
Giancarlo"giancarlo@example.work"

Despite the fact that the match on EmailAddress is defined as optional, the persons named "Michael" and "Rubens" are not returned. The reason is that the WHERE clause explicitly says that the value bound to the optional variable must start with the letter "g". For Michael, no value is found, hence the variable is equal to NULL, and the comparison operator fails on this. For Rubens, a value is found, but it does not start with the letter "g".

In query 2, however, a nested WHERE-clause is used. This specifies that any binding the optional expression does must begin with the letter "g", otherwise NULL is returned. The result of this query is:

NameEmailAddress
Michael 
Rubens 
Giancarlo"giancarlo@example.work"

The person "Michael" is returned without a result for his email address because there is no email address known for him at all. The person "Rubens" is returned without a result for his email address because, although he does have an email address, it does not start with the letter "g".

A query can contain at most one nested WHERE-clause per optional path expression, and at most one 'normal' WHERE-clause.

6.9. Other functions

Apart from the boolean functions and operators introduced in the previous section, SeRQL supports several other functions that return RDF terms rather than non-boolean values. These functions can be used in both the SELECT and the WHERE clause.

6.9.1. label(), lang() and datatype()

The three functions label(), lang() and datatype() all operate on literals. The result of the label() function is the lexical form of the supplied literal. The lang() function returns the language attribute. Both functions return their result as an untyped literal, which can again be compared with other literals using (in)equality-, comparison-, and like operators. The result of the datatype() function is a URI, which can be compared to other URIs. These functions can also be used in SELECT clauses, but not in path expressions.

An example query:

SELECT label(L)
FROM {R} rdfs:label {L}
WHERE isLiteral(L) AND lang(L) LIKE "en*"

6.9.2. namespace() and localName() (R1.2)

The functions namespace() and localName() operate on URIs. The namespace() function returns the namespace of the supplied URI, as a URI object. The localName() function returns the local name part of the supplied URI, as a literal. These functions can also be used in SELECT clauses, but not in path expressions.

The following query retrieves all properties of foaf:Person instances that are in the FOAF namespace. Notice that as a shorthand for the full URI, we can use a namespace prefix (followed by a colon) as an argument.

Data:

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

_:a  rdf:type         foaf:Person .
_:a  my:nick          "Schumi" .
_:a  foaf:firstName   "Michael" .
_:a  foaf:knows       _:b .

_:b  rdf:type         foaf:Person .
_:b  foaf:firstName   "Rubens" .
_:b  foaf:nick        "Rubinho" .

Query:

SELECT foafProp, Value
FROM {} foafProp {Value}
WHERE namespace(foafProp) = foaf:
USING NAMESPACE
    foaf = <http://xmlns.com/foaf/0.1/>

Result:

foafPropValue
<http://xmlns.com/foaf/0.1/firstName"Michael"
<http://xmlns.com/foaf/0.1/knows_:b
<http://xmlns.com/foaf/0.1/firstName"Rubens"
<http://xmlns.com/foaf/0.1/nick"Rubinho"

In the following example, the localName() function is used to match two equivalent properties from different namespaces (using the above data).

Query:

SELECT nick
FROM {} rdf:type {foaf:Person};
        nickProp {nick}
WHERE localName(nickProp) LIKE "nick"
USING NAMESPACE
    foaf = <http://xmlns.com/foaf/0.1/>

Result:

nick
"Schumi"
"Rubinho"

6.10. The LIMIT and OFFSET clauses

LIMIT and OFFSET allow you to retrieve just a portion of the results that are generated by the query. If a limit count is given, no more than that many results will be returned (but possibly less, if the query itself yields less results).

OFFSET says to skip that many results before beginning to return results. OFFSET 0 is the same as omitting the OFFSET clause. If both OFFSET and LIMIT appear, then OFFSET rows are skipped before starting to count the LIMIT results that are returned.

6.11. The USING NAMESPACE clause

The USING NAMESPACE clause can be used to define short prefixes for namespaces, which can then be used in abbreviated URIs. Multiple prefixes can be defined, but each declaration must have a unique prefix. The following query shows the use of namespace prefixes:

CONSTRUCT
    {Artist} rdf:type {art:Painter};
             art:hasPainted {Painting}
FROM
    {Artist} rdf:type {art:Artist};
             art:hasCreated {Painting} rdf:type {art:Painting}
USING NAMESPACE
    rdf = <http://www.w3.org/1999/02/22-rdf-syntax-ns#>,
    art = <http://example.org/arts/>

The query engine will replace every occurence of rdf: in an abbreviated URI with http://www.w3.org/1999/02/22-rdf-syntax-ns#, and art: with http://example.org/arts/. So art:hasPainted will be resolved to the URI http://example.org/arts/hasPainted.

Four namespaces that are used very frequently have been assigned prefixes by default:

Table 6.1. Default namespaces

PrefixNamespace
rdfhttp://www.w3.org/1999/02/22-rdf-syntax-ns#
rdfshttp://www.w3.org/2000/01/rdf-schema#
xsdhttp://www.w3.org/2001/XMLSchema#
owlhttp://www.w3.org/2002/07/owl#
serqlhttp://www.openrdf.org/schema/serql#

These prefixes can be used without declaring them. If either of these prefixes is declared explicitly in a query, this declaration will override the default mapping.

6.12. Built-in predicates

SeRQL contains a number of built-in predicates. These built-ins can be used like any other predicate, as part of a path expression. The difference with normal predicates is that the built-ins act as operators on the underlying rdf graph: they can be used to query for relations between RDF resources that are not explicitly modeled, nor immediately apparant from the RDF Semantics, but which are nevertheless very useful.

Currently, the following built-in predicates are supported:

  • {X} serql:directSubClassOf {Y}

    This relation holds for every X and Y where:

    1. X rdfs:subClassOf Y.
    2. X != Y.
    3. There is no class Z (Z != Y and Z != X) such that X rdfs:subClassOf Z and Z rdfs:subClassOf Y.
  • {X} serql:directSubPropertyOf {Y}

    This relation holds for every X and Y where:

    1. X rdfs:subPropertyOf Y.
    2. X != Y.
    3. There is no property Z (Z != X and Z != Y) such that X rdfs:subPropertyOf Z and Z rdfs:subPropertyOf Y.
  • {X} serql:directType {Y}

    This relation holds for every X and Y where:

    1. X rdf:type Y.
    2. There is no class Z (Z != Y) such that X rdf:type Z and Z rdfs:subClassOf Y.

Note: the above definition takes class/property equivalence through cyclic subClassOf/subPropertyOf relations into account. This means that if A rdfs:subClassOf B, and B rdfs:subClassOf A, it holds that A = B.

The namespace prefix 'serql' is built-in and does not have to be defined in the query.

6.13. Set combinatory operations

SeRQL offers three combinatory operations that can be used to combine sets of query results.

6.13.1. UNION (R1.2)

UNION is a combinatory operation the result of which is the set of query answers of both its operands. This allows one to specify alternatives in a query solution.

By default, UNION filters out duplicate answers from its operands. Specifying the ALL keyword ("UNION ALL") disables this filter.

The following example query retrieves the titles of books in the data, where the property used to describe the title can be either from the DC 1.0 or DC 1.1 specification.

Data:

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

_:a  dc10:title     "The SeRQL Query Language" .
_:b  dc11:title     "The SeRQL Query Language (revision 1.2)" .

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

Query:

SELECT title
FROM {book} dc10:title {title}

UNION

SELECT title
FROM {book} dc11:title {title}

USING NAMESPACE
    dc10 = <http://purl.org/dc/elements/1.0/>,
    dc11 = <http://purl.org/dc/elements/1.1/>

Result:

title
"The SeRQL Query Language"
"The SeRQL Query Language (revision 1.2)"
"SeRQL"
"SeRQL (updated)"

The union operator matches the projection items in order without taking the name of the projection item into account:

SELECT title, "1.0" AS "version"
FROM {book} dc10:title {title}

UNION

SELECT y, NULL
FROM {x} dc11:title {y}

USING NAMESPACE
    dc10 = <http://purl.org/dc/elements/1.0/>,
    dc11 = <http://purl.org/dc/elements/1.1/>

Result:

titleversion
"The SeRQL Query Language""1.0"
"The SeRQL Query Language (revision 1.2)" 
"SeRQL""1.0"
"SeRQL (updated)" 

SeRQL will use the names of the variables in the first operand of the union in the query result.

6.13.2. INTERSECT (R1.2)

The INTERSECT operation retrieves query results that occur in both its operands.

The following query only retrieves those album creators for which the name is specified identically in both DC 1.0 and DC 1.1.

Data:

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

_:a  dc10:creator     "George" .
_:a  dc10:creator     "Ringo" .

_:b  dc11:creator     "George" .
_:b  dc11:creator     "Ringo" .

_:c  dc10:creator     "Paul" .
_:c  dc11:creator     "Paul C." .

Query:

SELECT creator
FROM {album} dc10:creator {creator}

INTERSECT

SELECT creator
FROM {album} dc11:creator {creator}

USING NAMESPACE
    dc10 = <http://purl.org/dc/elements/1.0/>,
    dc11 = <http://purl.org/dc/elements/1.1/>

Result:

creator
"George"
"Ringo"

6.13.3. MINUS (R1.2)

The Minus operation returns query results from its first operand which do not occur in the results from its second operand.

The following query returns the titles of all albums of which "Paul" is not a creator.

Data:

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

_:a  dc10:creator     "George" .
_:a  dc10:title       "Sergeant Pepper" .

_:b  dc10:creator     "Paul" .
_:b  dc10:title       "Yellow Submarine" .

_:c  dc10:creator     "Paul" .
_:c  dc10:creator     "Ringo" .
_:c  dc10:title       "Let it Be" .

Query:

SELECT title
FROM {album} dc10:title {title}

MINUS

SELECT title
FROM {album} dc10:title {title};
             dc10:creator {creator}
WHERE creator like "Paul"

USING NAMESPACE
    dc10 = <http://purl.org/dc/elements/1.0/>,
    dc11 = <http://purl.org/dc/elements/1.1/>

Result:

title
"Sergeant Pepper"

6.14. NULL values

Just like SQL and most programming languages, SeRQL also has a NULL value. This value can be used just like any other value in SeRQL. For example, it can be used in the where clause to check that a literal doesn't have a datatype:

SELECT *
FROM {X} Y {Z}
WHERE isLiteral(Z) AND datatype(L) = NULL

6.15. Query Nesting

SeRQL has several constructs for nested queries. Nested queries can occur as operands for several boolean operators, which are explained in more detail in the following sections.

SeRQL applies variable scoping for nested queries. This means that when a variable is assigned in the outer query, its value will be carried over to the inner query when that variable is reused there.

6.15.1. The IN operator (R1.2)

The IN operator allows set membership checking where the set is defined by a nested SELECT-query.

The following example query uses the IN operator to retrieve all names of Persons, but only those names that also appear as names of Authors.

@prefix ex: <http://example.org/things#> .

_:a  rdf:type         ex:Person .
_:a  ex:name          "John" .

_:b  rdf:type         ex:Person .
_:b  ex:name          "Ringo" .

_:c  rdf:type         ex:Author .
_:c  ex:name          "John" .

_:d  rdf:type         ex:Author .
_:d  ex:name          "George" .

Query:

SELECT name
FROM {} rdf:type {ex:Person};
        ex:name {name}
WHERE name IN ( SELECT n
                FROM {} rdf:type {ex:Author};
                        ex:name {n}
              )
USING NAMESPACE
    ex = <http://example.org/things#>

Result:

name
"John"

6.15.2. ANY and ALL (R1.2)

The ANY and ALL keywords can be used for existential and universal quantification on the right operand of a boolean operator, if this operand is a set, defined by a nested query. The ALL keyword indicates that for every value of the nested query the boolean condition must hold. The ANY keyword indicates that the boolean condition must hold for at least one value of the nested query.

The following query selects the highest value from a set of values using the ALL keyword and a nested query.

Data:

@prefix ex:  <http://example.org/things#> .

_:a  ex:value     "10"^^xsd:int .
_:b  ex:value     "11"^^xsd:int .
_:c  ex:value     "12"^^xsd:int .
_:d  ex:value     "13"^^xsd:int .
_:e  ex:value     "14"^^xsd:int .

Query:

SELECT highestValue
FROM {node} ex:value {highestValue}
WHERE highestValue >= ALL ( SELECT value
                            FROM {} ex:value {value}
                          )
USING NAMESPACE
    ex = <http://example.org/things#>

Result:

highestValue
"14"^^xsd:int

6.15.3. EXISTS (R1.2)

EXISTS is a unary operator that has a nested SELECT-query as its operand. The operator is an existential quantifier that succeeds when the nested query has at least one result.

In the following example, we use EXIST to determine whether any authors are known that share a name with a person, and if so, to retrieve that person's names and hobbies.

Data:

@prefix ex: <http://example.org/things#> .

_:a  rdf:type         ex:Person .
_:a  ex:name          "John" .
_:a  ex:hobby         "Stamp collecting" .

_:b  rdf:type         ex:Person .
_:b  ex:name          "Ringo" .
_:b  ex:hobby         "Crossword puzzles" .

_:c  rdf:type         ex:Author .
_:c  ex:name          "John" .
_:c  ex:authorOf      "Let it be".

Query:

SELECT name, hobby
FROM {} rdf:type {ex:Person};
        ex:name {name};
        ex:hobby {hobby}
WHERE EXISTS ( SELECT n
               FROM {} rdf:type {ex:Author};
                       ex:name {n};
                       ex:authorOf {}
               WHERE n = name
             )
USING NAMESPACE
    ex = <http://example.org/things#>

Result:

namehobby
"John""Stamp collecting"

6.16. Example SeRQL queries

6.16.1. Query 1

Description: Find all papers that are about "RDF" and about "Querying", and their authors.

SELECT
   Author, Paper
FROM
   {Paper} rdf:type {foo:Paper};
           ex:keyword {"RDF", "Querying"};
           dc:author {Author}
USING NAMESPACE
   dc = <http://purl.org/dc/elements/1.0/>,
   ex = <http://example.org/things#>

Depicted as a graph, this query searches through the RDF graph for all subgraphs matching the following template:

Figure 6.7. Path expression for query 1

Path expression for query 1

6.16.2. Query 2

Description: Find all artefacts whose English title contains the string "night" and the museum where they are exhibited. The artefact must have been created by someone with first name "Rembrandt". The artefact and museum should both be represented by their titles.

SELECT DISTINCT
   label(ArtefactTitle), MuseumName
FROM
   {Artefact} arts:created_by {} arts:first_name {"Rembrandt"},
   {Artefact} arts:exhibited {} dc:title {MuseumName},
   {Artefact} dc:title {ArtefactTitle}
WHERE
   isLiteral(ArtefactTitle) AND
   lang(ArtefactTitle) = "en" AND
   label(ArtefactTitle) LIKE "*night*"
USING NAMESPACE
   dc   = <http://purl.org/dc/elements/1.0/>,
   arts = <http://example.org/arts/>

Again, depicted as a subgraph template:

Figure 6.8. Path expression for query 2

Path expression for query 2

Note that this figure only shows the path expressions from the from clause. The where clause poses additional constraints on the values of the variables which can't be as easily depicted graphically.

6.16.3. Query 3

Description: Find all siblings of class foo:bar.

SELECT DISTINCT
   Sibling
FROM
   {Sibling, <foo:bar>} rdfs:subClassOf {ParentClass}

Or graphically:

Figure 6.9. Path expression for query 3

Path expression for query 3

Note that the URI foo:bar is not returned as a result (there is an implicit constraint that doesn't allow Sibling to be equal to values that occur in the same multi-value node).

6.17. Comments/feedback

Feedback on this document and/or the SeRQL language is highly appreciated and can be posted on the forum at www.openrdf.org.

6.18. References

6.19. SeRQL grammar

The following is the BNF grammar of SeRQL, revision 1.2:

Query            ::= Table_query_set (Namespace_list)?
                   | Graph_query_set (Namespace_list)?

Namespace_list   ::= "using" "namespace" Namespace ("," Namespace)*
Namespace        ::= <PREFIX_NAME> "=" <FULL_URI>

Table_query_set  ::= Table_query (Set_operator Table_query_set)?
Table_query      ::= "(" Table_query_set ")"
                   | Select_query

Graph_query_set  ::= Graph_query (Set_operator Graph_query_set)?
Graph_query      ::= "(" Graph_query_set ")"
                   | Construct_query

Set_operator     ::= "union" | "minus" | "intersect"

Select_query     ::= "select" ("distinct")? Projection
                     ("from" Graph_pattern)?
                     ("limit" <POS_INTEGER>)?
                     ("offset" <POS_INTEGER>)?

Projection       ::= "*"
                   | Projection_elem ("," Projection_elem)*

Projection_elem  ::= Var_or_value ("as" <STRING>)?

Construct_query  ::= "construct" ("distinct")? Construct_clause
                     ("from" Graph_pattern)?
                     ("limit" <POS_INTEGER>)?
                     ("offset" <POS_INTEGER>)?

Construct_clause ::= "*"
                   | Path_expr_list

Graph_pattern    ::= Path_expr_list ("where" Boolean_expr)?

Path_expr_list   ::= Path_expr ("," Path_expr)*
Path_expr        ::= Path_expr_head ((";")? Path_expr_tail)?
                   | "[" Graph_pattern "]"
Path_expr_head   ::= Node Edge Node
Path_expr_tail   ::= Edge Node ((";")? Path_expr_tail)?
                   | "[" Edge Node ((";")? Path_expr_tail)? ("where" Boolean_expr)? "]"
                     (";" Path_expr_tail)?

Edge             ::= Var
                   | Uri
Node             ::= "{" (Node_elem_list)? "}"
Node_elem_list   ::= Node_elem  ("," Node_elem)*
Node_elem        ::= Var
                   | Uri
                   | BNode
                   | Literal
                   | Reified_stat
Reified_stat     ::= Node Edge Node

Boolean_expr     ::= And_expr ("or" Boolean_expr)?
And_expr         ::= Boolean_elem ("and" And_expr)?
Boolean_elem     ::= "(" Boolean_expr ")"
                   | "true"
                   | "false"
                   | "not" Boolean_elem
                   | Var_or_value Comp_op Var_or_value
                   | Var_or_value Comp_op ("any"|"all") "(" Table_query_set ")"
                   | Var_or_value "like" <STRING>
                   | Var_or_value "in" "(" Table_query_set ")"
                   | "exists" "(" Table_query_set ")"
                   | "isResource" "(" Var ")"
                   | "isURI" "(" Var ")"
                   | "isBNode" "(" Var ")"
                   | "isLiteral" "(" Var ")"

Comp_op          ::= "=" | "!=" | "<" | "<=" | ">" | ">="

Var_or_value     ::= Var | Value

Var              ::= <NC_NAME>
Value            ::= Uri
                   | BNode
                   | Literal
                   | "null"
                   | "datatype" "(" Var ")"
                   | "lang" "(" Var ")"
                   | "label" "(" Var ")"
                   | "namespace" "(" Var ")"
                   | "localname" "(" Var ")"

Uri              ::= <FULL_URI>
                   | <QNAME>

BNode            ::= <BNODE>

Literal          ::= (* A SeRQL literal, see section on literals *)
                   | <POS_INTEGER>
                   | <NEG_INTEGER>
                   | <DECIMAL>

<FULL_URI>       ::= "<" (* a legal URI, see http://www.ietf.org/rfc/rfc2396.txt *) ">"

<QNAME>          ::= <PREFIX_NAME> ":" <NC_NAME_CHAR>*

<BNODE>          ::= "_:" <NC_NAME>

<POS_INTEGER>    ::= "+"? [0-9]+
<NEG_INTEGER>    ::= "-" [0-9]+
<DECIMAL>        ::= ("+"|"-")? [0-9]* "." [0-9]+

<STRING>         ::= '"' (* zero or more (encoded) characters *) '"'

<PREFIX_NAME>    ::= <LETTER> <NC_NAME_CHAR>*
                   | "_" <NC_NAME_CHAR>+

<NC_NAME>        ::= (<LETTER>|"_") <NC_NAME_CHAR>*
<NC_NAME_CHAR>   ::= (* see http://www.w3.org/TR/REC-xml-names/#NT-NCNameChar *)
<LETTER>         ::= (* see http://www.w3.org/TR/REC-xml/#NT-Letter *)

Note: all keywords are assumed to be case-insensitive. Whitespace characters between tokens are not significant other than for separating the tokens. Production rules with a head that is surrounded by angular brackets define tokens (aka "terminals").