SPARQL Query Cheatsheet

SPARQL is a query language which is able to retrieve and manipulate data that is stored in RDF format. This cheatsheet will help you to create SPARQL queries.
It is generally similar to SQL as both query languages work with databases, just the format of the data is different in SPARQL.

TRIPLE PATTERN

Data stored in RDF normally has the triple form: subject, predicate and object. RDF data is normally stored in a linked graph. For example, Bob has an apple would be a linked graph with Bob and apple being nodes. Has would be an arc which goes from Bob to apple.
Below you can see a simple SPARQL query which returns the people contained in dbpedia which were born in Germany.
This query contains the single triple pattern ?people dbo:birthPlace res:Germany
It searches for all people(subject) which have their birthPlace(predicate) in Germany(object).
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX res: <http://dbpedia.org/resource/>
  SELECT *
  WHERE
   {
     ?people dbo:birthPlace res:Germany   
   } 

PREFIX

Generally: PREFIX label : [link]

You can add any prefix in connection with a label. It is located at the beginning of the query.

PREFIX dbo : [link]

Link for dbo, example http://dbpedia.org/ontology

PREFIX res : [link]

Link for resource, example: http://dbpedia.org/resource

PREFIX foaf : [link]

Link for a foaf(friend of a friend), which is a RDF vocabulary(ontology) to describe relations from a person to other people and objects.

SELECT

You can use SELECT to get rows from a database table. a = rdf:type

FROM

Syntax: SELECT var FROM <link> From specifies the target graph in the query.

Solution sequence modifiers

SELECT DISTINCT - removes duplicates from result.
ORDER BY ?var ASC/DESC (?property) - Sorts the elements by a certain property
PROJECTION - transformation of solution sequence into sequence containing subset of variables
OFFSET number - Makes the elements returned to start after the specified number of elements.
LIMIT number - Limits the amount of returned elements to a specified number.

WHERE

WHERE indicates where to get the rows from and under which condition the rows will be returned. ORDER BY is optional and is appended after the the WHERE portion of the query. It gives you the option to sort the rows by a certain property. Syntax: ORDER BY ASC/DESC (?property)

ASK

You can use ASK to check if a subquery has a solution. It returns true or false.

DESCRIBE

DESCRIBE returns an RDF graph which describes the resources which were found. Its output depends on each application. It normally returns triples in a table.

OPTIONAL

You can use optional when a condition should only be used when applicable. It tries to match a graph pattern and leaves the variable unbound if failed.

CONSTRUCT

CONSTRUCT returns an RDF graph which is constructed by substituting variables in triple templates.

Aggregate functions

SUM - returns the sum of all elements
AVG - returns the average of all elements
MAX - returns the row with the maximium value
MIN - returns the row with the minimum value
COUNT() - Counts the amount of elements per group
SAMPLE - returns a random element
GROUP_CONCAT - concats all elements together
These functions normally require a GROUP BY at the end of the query, on which the aggregate function should be applied to. Naming: <func> as ?var

Set theory in SPARQL

A ∪ B = { A. } UNION { B. }
A ∩ B = A. B.
A \ B = A. FILTER NOT EXISTS{ B. }

String conversion functions

IRI(string) converts a string into an IRI.
STR(value) converts a value into a string.

String functions

STRLEN(string) - returns the length of a string.
SUBSTR(string,beginpos,length) - returns a substring of a given string.
LCASE(string) - returns a string in lowercase.
UCASE(string) - returns a string in uppercase.
STRSTARTS(string,comparestring) - compares if a string starts with the comparestring.
STRENDS(string,comparestring) - compares if a string ends with the comparestring.
CONTAINS(string,comparestring) - compares if a string contains the comparestring somewhere within the string.
STRBEFORE(string,comparestring) - returns the part of the string before the comparestring if contained in the string. If not, it returns ""
STRAFTER(string,comparestring) - returns the part of the string after the comparestring if contained in the string. If not, it returns ""
ENCODE_FOR_URI(string) - encodes an string to a URI(ex: a space is converted into %20).
CONCAT(string1,string2,string3,...) - returns a concated string.
LANGMATCHES(languagetag, languagerange) - checks if the range matches the language tag.
REGEX(string,pattern,flag) - checks a string by a specific regex pattern

FILTER

You can use filter to filter the results by a certain condition. Syntax: filter (cond)
Built in filter functions
Logical: !(NOT), &&(AND), ||(OR)
Math: +, -, *, /
Comparison: =, !=, >, < , IN(low,high), ..
SPARQL tests: isURI, isBlank, isLiteral, bound
SPARQL accessors: str, lang, datatype
Other: sameTerm, langMatches, regex)

SPARQL Tests

isURI(?var) - returns true if term is a URI
isBlank(?var) - returns true if term is a blank node
isLiteral(?var) - returns true if term is a literal
bound(?var) - returns true if a variable is bound to a value. If not, it returns false
isIRI(?var) - returns true if term is a IRI