SPARQL/Expressions and Functions

BIND
The  clause can be used to assign the result of an expression to a variable (usually a new variable, but you can also overwrite existing ones).

can also be used to simply bind constant values to variables in order to increase readability. For example, a query that finds all female priests:

The above gives the same result as

IF
The  expressions are used to assign different values based on a condition.

For instance to calculate the age, precisely to the day. In the expression  the condition determines to subtract 1 or 0 (nothing) from the   based on the month and the day of the birth and the death.

Here an example to divide population in groups. The  in the   shows it in different colors.

Operators
The familiar mathematical operators are available:,  ,  ,   to add, subtract, multiply or divide numbers.

The operators,  ,  ,  ,   are available to compare values. Comparison is also defined for other types; for example,  is true (lexical comparison), as is   and. The inequality test ≠ is written. The  can also be used as a prefix to functions that results a boolean like   and.

Boolean conditions can be combined with  (logical and:   is true if both   and   are true) and   (logical or:   is true if either (or both) of   and   is true).

Examples  and.

VALUES
The  clause generates a variable with one or more values. The values can be of any type, like numeric, strings, or even items, like,   or

Values can have more dimensions too. The dimensions are grouped by like.

DATATYPE
Each value in SPARQL has a type, which tells you what kind of value it is and what you can do with it. The most important types are:


 * item, like  for.
 * boolean, with the two possible values  and  . Boolean values aren’t stored in statements, but many expressions return a boolean value, e. g.    or.
 * string, a piece of text. String literals are written in double quotes.
 * monolingual text, a string with a language tag attached. In a literal, you can add the language tag after the string with an  sign, e. g..
 * numbers, either integers or decimals.
 * dates. Date literals can be written by adding  (case sensitive –   won’t work!) to an ISO 8601 date string:.

Some datatypes are rdf:langString, xsd:string, xsd:integer, xsd:dateTime, xsd:decimal or "".

STR
The  function converts values to a string. It also resolves prefixes, for instance wd:Q1339 will be converted into http://www.wikidata.org/entity/Q1339. The reversal of this is the, which will convert a string to an IRI.

IRI
the, which will convert a string to an IRI, by applying the prefixes.

In the example below a Predicate like  get converted to a string http://www.wikidata.org/prop/direct/P569. To get a Label for the predicate it first needs to be replaced to get an entity ( http://www.wikidata.org/entity/P569 ), which with  gets converted to. The label of this can then be displayed as "".

LANG
The  function retrieves the language tag of Labels, Descriptions, Aliases and of Monolingual texts.

BOUND
The function  returns true if variable is bound to a value. It returns false otherwise. The  expression is used often with   expressions. For example, suppose you have a query that shows some humans, and instead of just showing their label, you’d like to display their if they have one, and only use the label if a pseudonym doesn’t exist. For this, you select the pseudonym in an  clause (it has to be optional – you don’t want to throw out results that don’t have a pseudonym), and then use   to select either the pseudonym or the label.

IN and NOT IN
The function  checks if a value is found in a list of values. For example  is true. A similar function  checks if a value is not found in a list of values.

isBLANK
The  expression checks if a value is an "unknown value".

Wikidata value can also have special value "no value". With normal triples this simply results in the absence of a result.

The prefix  selects the "no value" node. The code  is a special word.

STRLEN
The function  returns the length of a string. For instance  where   is "ABC" will return 3.

SUBSTR
The function  returns a substring of a string beginning at the position marked by beginposition, and will have a length as indicated. For instance  where   = "ABCDEFGH" will return "BCD". A substring without length like  will return "BCDEFGH".

UCASE
The function  returns the string in Upper case. For instance a string "Abc" will be returned as "ABC".

LCASE
The function  returns the string in Lower case. For instance a string "Abc" will be returned as "abc".

STRSTARTS
The function  checks if the string starts with the compare string. For instance  returns true, indicating that the string starts with "ABC".

STRENDS
The function  checks if the string ends with the compare string. For instance  returns true, indicating that the string ends with "FGH".

CONTAINS
The function  checks if the string contains the compare string. For instance  returns true, indicating that the string contains "DEF".

STRBEFORE
The function  returns the part of the string before the compare string. For instance  returns "ABC". If the compare string is not found it returns "".

STRAFTER
The function  returns the part of the string after the compare string. For instance  returns "GH". If the compare string is not found, it returns "".

ENCODE_FOR_URI
The function  converts the special characters in the string, to be able to use it in an web URL. For instance  returns "ABC%20D%C3%8BFGH". The reverse of this function is.

CONCAT
The function  returns the concatenation of 2 or more strings. For instance  returns "ABCDEFGHXYZ".

LANGMATCHES
The function  checks if the language tag matches the language range. For example this code  filters labels in the french language. It is similar to  with the difference that the LANGMATCHES filter will also output language tags with regions, e.g. "fr-BE" while   will only output the strings with the exact tag "fr". A language range of "*" matches any non-empty language-tag string.

REGEX
The function  checks if the string matches the pattern. It is mostly used in a  clause like.

The pattern may contain different special characters. Blazegraph instances such as the Wikidata Query Service interpret the pattern as a Java, which is a subset of ICU regular expressions. The table below lists the most common special characters:

The flag is optional. Flag "i" means the match is case-insensitive.

Examples

PS: A single \ is used as an escape symbol in strings, so \\ is used to indicate a single \.
 * 1) title might be a rhyme
 * 2) title is an alliteration

REPLACE
The function  returns the string after replacing all occurrences of   in   with. is interpreted the same way as in. The  can contain   or , which are replaced by the corresponding numbered or named capture group in the pattern. An optional  affects the regular expression pattern, just as with the   argument to. For example,  returns "ABC_def_GH". removes all the vowels from the original string.

ABS
The function  returns the absolute value of a number. For instance,  returns 1.

ROUND
The function  returns the rounded value of a number. For instance,  returns 1, while   returns 2.

CEIL
The function  returns the largest number (round up). For instance, both  and   return 2.

FLOOR
The function  returns the smallest number (round down). For instance, both  and   return 1.

RAND
The function  returns a random value between 0 and 1. For instance,  returns 0.7156405780739334.

COUNT, MIN, MAX, AVG and SUM
The functions,  ,  ,  , and   can only be used as Aggregate functions.

For instance,  does NOT work. Instead, use the expression.

NOW
The function  returns the current date and time.

With constructions like  it is possible to add or subtract days from the current date. will add 1 month. will add 1 year. You can add or subtract any combination of years, months, days and even hours, minutes and seconds using.

YEAR, MONTH and DAY
The function  returns the year of the date value. The functions  and   return the month or day.

HOURS, MINUTES and SECONDS
The function  returns the hour of the date value. The functions  and   returns the minutes or seconds. Currently Wikidata does not hold date values in hour, minutes or seconds.

TIMEZONE and TZ
The function  returns the time zone of the date value. Currently in Wikidata all dates have a  of "PT0S" for UTC. Other valid values would be between -PT14H and PT14H indicating the time offset in hours.

The function  returns the time zone as a simple literal of the date value. Currently in Wikidata all dates have a  of "Z" for UTC.

Example with dates

geof:distance
The function  returns distance between two points, in kilometers.

Example usage:

geof:longitude and geof:latitude
The functions  and   convert a well-known text literal () of a Point geometry to its longitude and latitude, respectively.

Example usage:

wikibase:geoLongitude and wikibase:geoLatitude
It is also possible to retrieve the longitude and latitude of a coordinate node using  and   qualifiers. See here for an explanation.

AUTO_COORDINATES
The code  returns the current location, if you allow your browser to use it.

Aggregate functions
See Aggregate functions for COUNT, MIN, MAX, SUM, AVG, SAMPLE and GROUP_CONCAT