SHACL 1.2 SPARQL Extensions

W3C Working Draft

More details about this document
This version:
https://www.w3.org/TR/2026/WD-shacl12-sparql-20260731/
Latest published version:
https://www.w3.org/TR/shacl12-sparql/
Latest editor's draft:
https://w3c.github.io/data-shapes/shacl12-sparql/
History:
https://www.w3.org/standards/history/shacl12-sparql/
Commit history
Test suite:
https://w3c.github.io/data-shapes/data-shapes-test-suite/
Latest Recommendation:
https://www.w3.org/TR/2017/REC-shacl-20170720/#part2
Editors:
(TopQuadrant, Inc.)
(Corning)
(JPMorgan Chase & Co.)
(Swansea University)
Former editor:
Dimitris Kontokostas
Feedback:
GitHub w3c/data-shapes (pull requests, new issue, open issues)
public-shacl@w3.org with subject line [shacl12-sparql] (archives)

Abstract

This document defines SPARQL-related extensions of the SHACL Shapes Constraint Language. While the Core part of SHACL defines the basic syntax of shapes and the most common constraint components supported by SHACL, the SPARQL-related extensions cover features that extend the expressiveness of Core by means of SPARQL. In particular, this document defines how constraints and constraint components can be defined using SPARQL. Furthermore, this document introduces SPARQL-based node expressions that can be used to derive lists of nodes. Finally, this document defines SPARQL-based inference rules that can be used in conjunction with shapes.

Status of This Document

This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C standards and drafts index.

This document was published by the Data Shapes Working Group as a Working Draft using the Recommendation track.

Publication as a Working Draft does not imply endorsement by W3C and its Members.

This is a draft document and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to cite this document as other than a work in progress.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent that the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 18 August 2025 W3C Process Document.

SHACL Specifications

This specification is part of the SHACL 1.2 family of specifications. See the SHACL 1.2 Overview for a more detailed introduction to them.

The specifications are as follows:

Working Drafts:

SHACL 1.2 Core
defines the Core of SHACL
SHACL 1.2 SPARQL Extensions
defines SPARQL-related extensions of SHACL
SHACL 1.2 Node Expressions
defines expressions used to derive focus nodes and value nodes in SHACL
SHACL 1.2 Rules
defines SHACL's methods of rule-based inference
SHACL 1.2 UI
defines SHACL's use for User Interface generation
SHACL 1.2 Profiling
defines the use of SHACL for profiling data, including SHACL data

Working Group Note Drafts:

SHACL 1.2 Overview
overviews the set of SHACL specifications
SHACL 1.2 Compact Syntax
defines an RDF syntax for expressing SHACL concepts
Note

Implementers can partially check their level of conformance with the above specifications by successfully passing the test cases of the SHACL 1.2 test suite. Note, however, that passing all the tests in the test suite does not imply complete conformance to the specifications. It only implies that the implementation conforms to the aspects tested by the test suite.

1. Introduction

This document specifies the SPARQL-related features of the SHACL (Shapes Constraint Language).

1.1 Terminology

Throughout this document, the following terminology is used.

The SHACL SPARQL Extensions defined in this document are sometimes called SHACL-SPARQL.

Terminology that is linked to portions of RDF 1.2 Concepts and Abstract Syntax is used in SHACL-SPARQL as defined there. Terminology that is linked to portions of SPARQL 1.2 Query Language is used in SHACL-SPARQL as defined there. Terminology that is linked to portions of SHACL 1.2 Core is used in SHACL-SPARQL as defined there. A single linkage is sufficient to provide a definition for all occurences of a particular term in this document.

Definitions are complete within this document, i.e., if there is no rule to make some situation true in this document then the situation is false.

Basic RDF Terminology
This document uses the terms RDF graph, RDF triple, IRI, literal, blank node, node of an RDF graph, datatype, RDF term, and subject, predicate, and object of RDF triples as defined in RDF 1.2 Concepts and Abstract Syntax [rdf12-concepts].
Binding, Solution
A binding is a pair (variable, RDF term), consistent with the term's use in [sparql12-query]. A solution is a set of bindings where each variable must be unique. Informally, a solution is often understood as one row in the body of the result table of a SPARQL query.

1.2 Document Conventions

The syntax of SHACL is RDF. The examples in this document use Turtle [rdf12-turtle]. Other RDF serializations such as RDF/XML may be used in practice. The reader should be familiar with basic RDF concepts [rdf12-concepts] such as triples and with SPARQL [sparql12-query].

Within this document, the following namespace prefix bindings are used:

Prefix Namespace
owl: http://www.w3.org/2002/07/owl#
rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
rdfs: http://www.w3.org/2000/01/rdf-schema#
sh: http://www.w3.org/ns/shacl#
xsd: http://www.w3.org/2001/XMLSchema#
ex: http://example.com/ns#

Within this document, the following JSON-LD context is used:

{
  "@context": {
    "owl": "http://www.w3.org/2002/07/owl#",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
    "sh": "http://www.w3.org/ns/shacl#",
    "xsd": "http://www.w3.org/2001/XMLSchema#",
    "ex": "http://example.com/ns#"
  }
}

Note that the URI of the graph defining the SHACL vocabulary itself is equivalent to the namespace above, i.e. it includes the #. References to the SHACL vocabulary, e.g. via owl:imports should include the #.

Throughout the document, color-coded boxes containing RDF graphs in Turtle will appear. These fragments of Turtle documents use the prefix bindings given above.

SHACL Definitions appear in blue boxes:

SPARQL or TEXTUAL DEFINITIONS
# This box contains SPARQL or textual definitions.

Grey boxes such as this include syntax rules that apply to the shapes graph.

SPARQL variables using the $ marker represent external bindings that are pre-bound or, in the case of $PATH, substituted in the SPARQL query before execution (as explained in 4.3 Validation with SPARQL-based Constraint Components).

true denotes the RDF term "true"^^xsd:boolean. false denotes the RDF term "false"^^xsd:boolean.

1.3 Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words MAY, MUST, and SHOULD in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.

This document defines the SHACL-SPARQL language that extends SHACL Core. This specification describes conformance criteria for:

Also see the discussion of well-formedness in the Conformance section of SHACL Core.

2. Prefix Declarations for SPARQL Queries

This section introduces the mechanisms that are used throughout this document to declare namespace prefixes for SPARQL queries.

A shapes graph may include declarations of namespace prefixes so that these prefixes can be used to abbreviate the SPARQL queries derived from the same shapes graph. The syntax of such prefix declarations is illustrated by the following example.

IRIs or blank nodes that have values for both sh:prefix and sh:namespace are called prefix declarations. The SHACL vocabulary includes the class sh:PrefixDeclaration as type for such prefix declarations although no rdf:type triple is required for them. Prefix declarations have exactly one value for the property sh:prefix. The values of sh:prefix are literals of datatype xsd:string. Prefix declarations have exactly one value for the property sh:namespace. The values of sh:namespace are literals of datatype xsd:anyURI or xsd:string. Such a pair of values specifies a single mapping of a prefix to a namespace. The values of the property sh:declare are prefix declarations.

The recommended subject for values of sh:declare is the IRI of the named graph containing the shapes that use the prefixes. These IRIs are often declared as an instance of sh:ShapesGraph or owl:Ontology, but this is not required.

Among others, Prefix declarations can be used by SPARQL-based constraints, the validators of SPARQL-based constraint components, SPARQL-based node expressions, and SPARQL-based inference rules. These nodes can use the property sh:prefixes to specify a set of prefix mappings. An example use of the sh:prefixes property can be found in this example.

The values of sh:prefixes are either IRIs or blank nodes. A SHACL processor collects a set of prefix mappings as the union of all individual prefix mappings that are values of the SPARQL property path sh:prefixes/(^owl:versionIRI?/owl:imports)*/sh:declare of the SPARQL-based constraint or validator. The ^owl:versionIRI? element supports graphs that are imported by owl:versionIRI, navigating from the version IRI to the shapes graph IRI before following further owl:imports. If such a collection of prefix declarations contains multiple different namespaces for the same value of sh:prefix, then the shapes graph is ill-formed. (Note that SHACL processors MAY ignore prefix declarations that are never reached).

If a SPARQL query has no value for sh:prefixes then the system will use those prefix declarations from the shapes graph that are values of sh:declare at a SHACL instance of owl:Ontology, sh:DataGraph, sh:ShapesGraph, or sh:RulesGraph (which is a subclass of sh:ShapesGraph).

A SHACL processor transforms the values of sh:select (and similar properties such as sh:ask and sh:construct) into SPARQL by prepending PREFIX declarations for all prefix mappings. Each value of sh:prefix is turned into the PNAME_NS, while each value of sh:namespace is turned into the IRIREF in the PREFIX declaration. For the example shapes graph above, a SHACL-SPARQL processor would produce lines such as PREFIX ex: <http://example.com/ns#>. The SHACL-SPARQL processor MUST produce a failure if the resulting query string cannot be parsed into a valid SPARQL 1.2 query.

In the rest of this document, the sh:prefixes statements may have been omitted for brevity.

3. SPARQL-based Constraints

SHACL-SPARQL supports a constraint component that can be used to express restrictions based on a SPARQL SELECT query.

Constraint Component IRI: sh:SPARQLConstraintComponent

Parameters:
Property Summary
sh:sparql A SPARQL-based constraint declaring the SPARQL query to evaluate.

The syntax rules and validation process for SPARQL-based constraints are defined in the rest of this section.

3.1 An Example SPARQL-based Constraint

This section is non-normative.

The following example illustrates the syntax of a SPARQL-based constraint.

The SPARQL query returns result set solutions for all bindings of the variable value that violate the constraint. There is a validation result for each solution in that result set, applying the mapping rules explained later. In this example, each validation result will have the binding for the variable this as the sh:focusNode, ex:germanLabel as sh:resultPath and the violating value as sh:value.

The following example illustrates a similar scenario as above, but with a property shape.

3.2 Syntax of SPARQL-based Constraints

Shapes may have values for the property sh:sparql, and these values are either IRIs or blank nodes. These values are called SPARQL-based constraints.

SPARQL-based constraints have exactly one value for the property sh:select. The value of sh:select is a literal of datatype xsd:string. The class sh:SPARQLConstraint is defined in the SHACL vocabulary and may be used as the type of these constraints (although no type is required). Using the prefix handling rules, the value of sh:select is a valid SPARQL 1.2 SELECT query. The SPARQL query derived from the value of sh:select projects the variable this in the SELECT clause.

The following two properties are similar to their use in shapes:

SPARQL-based constraints may have values for the property sh:message and these are literals with datatype xsd:string, rdf:dirLangString, rdf:langString, or rdf:HTML. There should neither be more than one value for sh:message with the same language tag, nor multiple values with datatype xsd:string. SPARQL-based constraints may have at most one value for the property sh:deactivated and this value is either true or false. SPARQL-based constraints may have at most one value for the property sh:severity and this value is an IRI.

SELECT queries used in the context of property shapes use a special variable named PATH as a placeholder for the path used by the shape.

The only legal use of the variable PATH in the SPARQL queries of SPARQL-based constraints and SELECT-based validators is in the predicate position of a triple pattern. A query that uses the variable PATH in any other position is ill-formed.

3.3 Validation with SPARQL-based Constraints

This section explains the validator of sh:SPARQLConstraintComponent. Note that this validator only explains one possible implementation strategy, and SHACL processors may choose alternative approaches as long as the outcome is equivalent.

TEXTUAL DEFINITION
Let $sparql be a value of sh:sparql. There are no validation results if the SPARQL-based constraint has true as a value for the property sh:deactivated. Otherwise, execute the SPARQL query specified by the SPARQL-based constraint $sparql pre-binding the variable this as described in 3.3.1 Pre-bound variable $this in SPARQL Constraints. If the shape is a property shape, then prior to execution substitute the variable PATH where it appears in the predicate position of a triple pattern with a valid SPARQL surface syntax string of the SHACL property path specified via sh:path at the property shape. There is one validation result for each solution that does not have true as the binding for the variable failure. These validation results MUST have the property values explained in 3.3.2 Mapping of Solution Bindings to Result Properties. If $sparql has a value for sh:severity then the validation result MUST have that value as its (only) sh:resultSeverity. A failure MUST be produced if and only if one of the solutions has true as the binding for failure.

3.3.1 Pre-bound variable $this in SPARQL Constraints

When the SPARQL queries of SPARQL-based constraints and the validators of SPARQL-based constraint components are processed, the SHACL-SPARQL processor pre-binds values for the variable $this to the current focus node.

3.3.2 Mapping of Solution Bindings to Result Properties

The property values of the validation result nodes are derived by the following rules, through a combination of result solutions and the values of the constraint itself. The rules are meant to be executed from top to bottom, so that the first bound value will be used.

Property Production Rules
sh:focusNode
  1. The binding for the variable this
sh:resultPath
  1. The binding for the variable path, if that is a IRI
  2. For results produced by a property shape, a SHACL property path that is equivalent to the value of sh:path of the shape
sh:value
  1. The binding for the variable value
  2. The value node
sh:resultMessage
  1. The binding for the variable message
  2. For SPARQL-based constraints: The values of sh:message of the SPARQL-based constraint. For SPARQL-based constraint components: The values of sh:message of the validator of the SPARQL-based constraint component.
  3. For SPARQL-based constraint components: The values of sh:message of the SPARQL-based constraint component.
  4. The default mechanisms for declaring messages at the shape or constraint apply otherwise.
These message literals may include the names of any SELECT result variables via {?varName} or {$varName}. If the constraint is based on a SPARQL-based constraint component, then the component's parameter names can also be used. These {?varName} and {$varName} blocks SHOULD be replaced with suitable string representations of the values of said variables.
sh:sourceConstraint
  1. The SPARQL-based constraint, i.e. the value of sh:sparql

4. SPARQL-based Constraint Components

SPARQL-based constraints provide a lot of flexibility but may be hard to understand for some people or lead to repetition. This section introduces SPARQL-based constraint components as a way to abstract the complexity of SPARQL and to declare high-level reusable components similar to the Core constraint components. Such constraint components can be declared using the SHACL RDF vocabulary and thus shared and reused.

4.1 An Example SPARQL-based Constraint Component

This section is non-normative.

The following example demonstrates how SPARQL can be used to specify new constraint components using the SHACL-SPARQL language. The example implements sh:pattern and sh:flags using a SPARQL ASK query to validate that each value node matches a given regular expression. Note that this is only an example implementation and should not be considered normative.

Once the constraint component has been declared, its parameters can be used in a shape as illustrated in the following example.

Constraint components provide instructions to validation engines on how to identify and validate constraints within a shape. In general, if a shape S has a value for a property p, and there is a constraint component C that specifies p as a parameter, and S has values for all mandatory parameters of C, then the set of these parameter values (including the optional parameters) declare a constraint and the validation engine uses a suitable validator from C to perform the validation of this constraint. In the example above, sh:PatternConstraintComponent declares the mandatory parameter sh:pattern, the optional parameter sh:flags, and a validator that can be used to perform validation against either node shapes or property shapes.

4.2 Syntax of SPARQL-based Constraint Components

A SPARQL-based constraint component is an IRI that has SHACL type sh:ConstraintComponent in the shapes graph.

The mechanism to declare new constraint components in this document is limited to those based on SPARQL. However, the general syntax of declaring parameters and validators has been designed to also work for other extension languages such as JavaScript.

4.2.1 Parameter Declarations (sh:parameter)

The parameters of a constraint component are declared via the property sh:parameter. The values of sh:parameter are called parameter declarations. The class sh:Parameter may be used as type of parameter declarations but no such triple is required. Each parameter declaration has exactly one value for the property sh:path. At parameter declarations, the value of sh:path is an IRI.

The local name of an IRI is defined as the longest NCNAME at the end of the IRI, not immediately preceded by the first colon in the IRI. The parameter name of a parameter declaration is defined as the local name of the value of sh:path. To ensure that a correct mapping from parameters into SPARQL variables is possible, the following syntax rules apply:

Every parameter name is a valid SPARQL VARNAME. Parameter names must not be one of the following: this, path, PATH, value. A constraint component where two or more parameter declarations use the same parameter names is ill-formed.

The values of sh:optional must be literals with datatype xsd:boolean. A parameter declaration can have at most one value for the property sh:optional. If set to true then the parameter declaration declares an optional parameter. Every constraint component has at least one non-optional parameter.

The class sh:Parameter is defined as a SHACL subclass of sh:PropertyShape, and all properties that are applicable to property shapes may also be used for parameters. This includes descriptive properties such as sh:name and sh:description but also constraint parameters such as sh:class. Shapes that do not conform with the constraints declared for the parameters are ill-formed. Some implementations MAY use these constraint parameters to prevent the execution of constraint components with invalid parameter values.

4.2.2 Label Templates (sh:labelTemplate)

The property sh:labelTemplate can be used at any constraint component to suggest how constraints could be rendered to humans. The values of sh:labelTemplate are strings (possibly with language tag) and are called label templates.

The remainder of this section is non-normative.

Label templates can include the names of the parameters that are declared for the constraint component using the syntaxes {?varName} or {$varName}, where varName is the name of the parameter name. At display time, these {?varName} and {$varName} blocks should be replaced with the actual parameter values. There may be multiple label templates for the same subject, but they should not have the same language tags and there should not be more than one template with datatype xsd:string.

4.2.3 Validators

For every supported shape type (i.e., property shape or node shape) the constraint component declares a suitable validator. For a given constraint, a validator is selected from the constraint component using the following rules, in order:

  1. For node shapes, use one of the values of sh:nodeValidator, if present.
  2. For property shapes, use one of the values of sh:propertyValidator, if present.
  3. Otherwise, use one of the values of sh:validator.

If no suitable validator can be found, a SHACL-SPARQL processor ignores the constraint.

SHACL-SPARQL includes two types of validators, based on SPARQL SELECT (for sh:nodeValidator and sh:propertyValidator) or SPARQL ASK queries (for sh:validator).

4.2.3.1 SELECT-based Validators

Validators with SHACL type sh:SPARQLSelectValidator are called SELECT-based validators. The values of sh:nodeValidator must be SELECT-based validators. The values of sh:propertyValidator must be SELECT-based validators. SELECT-based validators have exactly one value for the property sh:select. The value of sh:select is a valid SPARQL SELECT query using the aforementioned prefix handling rules. The SPARQL query derived from the value of sh:select projects the variable this in its SELECT clause.

The remainder of this section is non-normative.

The following example illustrates the declaration of a constraint component based on a SPARQL SELECT query. It is a generalized variation of the example from 3.1 An Example SPARQL-based Constraint. Where that SPARQL query included two constants: the specific property ex:germanLabel and the language tag de, this example generalizes the constraint so that any property can be defined with a language tag. In practice, the constraint component is applied by adding the parameter predicate(s) to a shape (e.g., ex:lang "de"), which a SHACL-SPARQL processor pre-binds to the corresponding SPARQL variable(s) (e.g., $lang) before executing the SELECT validator. Constraint components make it possible to generalize such scenarios, so that constants get pre-bound with parameters. This allows the query logic to be reused in multiple places, without having to write any new SPARQL.

Once a constraint component has been declared (in a shapes graph), its parameters can be used as illustrated in the following example. Any property shape that includes ex:lang is interpreted as using ex:LanguageConstraintComponentUsingSELECT (binding $lang to that value).

The example shape above specifies the condition that all values of ex:germanLabel carry the language tag de while all values of ex:englishLabel have en as their language. These details are specified via two property shapes that have values for the ex:lang parameter required by the constraint component.

4.2.3.2 ASK-based Validators

Many constraint components are of the form in which all value nodes are tested individually against some boolean condition. Writing SELECT queries for these becomes burdensome, especially if a constraint component can be used for both property shapes and node shapes. SHACL-SPARQL provides an alternative, more compact syntax for validators based on ASK queries.

Validators with SHACL type sh:SPARQLAskValidator are called ASK-based validators. The values of sh:validator must be ASK-based validators. ASK-based validators have exactly one value for the property sh:ask. The value of sh:ask must be a literal with datatype xsd:string. The value of sh:ask must be a valid SPARQL ASK query using the aforementioned prefix handling rules.

The remainder of this section is non-normative.

The ASK queries return true if and only if a given value node (represented by the pre-bound variable value) conforms to the constraint.

The following example declares a constraint component using an ASK query.

Note that the validation condition implemented by an ASK query is "in the inverse direction" from its SELECT counterpart: ASK queries return true for value nodes that conform to the constraint, while SELECT queries return those value nodes that do not conform.

4.3 Validation with SPARQL-based Constraint Components

This section defines the validator of SPARQL-based constraint components. Note that this validator only explains one possible implementation strategy, and SHACL processors may choose alternative approaches as long as the outcome is equivalent.

As the first step, a validator MUST be selected based on the rules outlined in 4.2.3 Validators. Then the following rules apply, producing a set of solutions of SPARQL queries:

The SPARQL query executions above MUST pre-bind the variable this as described in 3.3.1 Pre-bound variable $this in SPARQL Constraints. In addition, each value of a parameter of the constraint component in the constraint MUST be pre-bound as a variable that has the parameter name as its name.

The production rules for the validation results are identical to those for SPARQL-based constraints, using the solutions QS as produced above.

5. Annotation Properties

This section extends the general mechanism to produce validation results using SPARQL-based constraints or constraint components.

Implementations that support this feature make it possible to inject annotation properties into the validation result nodes created for each solution produced by the SELECT queries of a SPARQL-based constraint or constraint component. Any such annotation property needs to be declared via a value of sh:resultAnnotation at the subject of the sh:select or sh:ask triple.

The values of sh:resultAnnotation are called result annotations and are either IRIs or blank nodes.

Result annotations have the following properties:

Property Summary and Syntax Rules
sh:annotationProperty The property that shall be set. Each result annotation has exactly one value for the property sh:annotationProperty and this value is an IRI.
sh:annotationVarName The name of the SPARQL variable to take the annotation values from. Each result annotation has at most 1 value for the property sh:annotationVarName and this value is literal with datatype xsd:string.
sh:annotationValue Constant RDF terms that shall be used as default values.

For each solution of a SELECT result set, a SHACL processor that supports annotations walks through the declared result annotations. The mapping from result annotations to SPARQL variables uses the following rules:

  1. Use the value of the property sh:annotationVarName
  2. If no such value exists, use the local name of the value of sh:annotationProperty as the variable name.

If a variable name could be determined, then the SHACL processor copies the binding for the given variable as a value for the property specified using sh:annotationProperty into the validation result that is being produced for the current solution. If the variable has no binding in the result set solution, then the values of sh:annotationValue are used, if present.

Here is an example illustrating the use of result annotations.

ex:AnnotationExample
	a sh:NodeShape ;
	sh:targetNode ex:ExampleResource ;
	sh:sparql [   # _:b1
		sh:resultAnnotation [
			sh:annotationProperty ex:time ;
			sh:annotationVarName "time" ;
		] ;
		sh:select """
			SELECT $this ?message ?time
			WHERE {
				BIND (CONCAT("The ", "message.") AS ?message) .
				BIND (NOW() AS ?time) .
			}
			""" ;
	] .

Validation produces the following validation report:

[	a sh:ValidationReport ;
	sh:conforms false ;
	sh:result [
		a sh:ValidationResult ;
		sh:focusNode ex:ExampleResource ;
		sh:resultMessage "The message." ;
		sh:resultSeverity sh:Violation ;
		sh:sourceConstraint _:b1 ;
		sh:sourceConstraintComponent sh:SPARQLConstraintComponent ;
		sh:sourceShape ex:AnnotationExample ;
		ex:time "2015-03-27T10:58:00"^^xsd:dateTime ;  # Example
	]
] .

6. SPARQL-based Node Expressions

This section introduces node expression functions based on SPARQL.

6.1 Select Expressions

A node expression that has a value for sh:select is called a select expression with the function name sh:SelectExpression.

A node in an RDF graph is a well-formed select expression if it is a blank node that has exactly one value for the predicate sh:select and this value is a literal with datatype xsd:string. A well-formed select expression can have at most one value for the property sh:prefixes and this value can only be an IRI or a blank node.

Using the prefix handling rules, the value of sh:select is a valid SPARQL 1.2 SELECT query. The SPARQL query derived from the value of sh:select projects exactly one variable in the SELECT clause.

EVALUATION OF SELECT EXPRESSIONS

The output nodes of a select expression are the list resultNodes consisting of exactly the bindings of the (only) variable that is projected from the SELECT clause when the query is evaluated against the focus graph. The value of focusNode is pre-bound as the value of the SPARQL variable this. The value of each scope variable is pre-bound as a SPARQL variable with the same name and value. A failure is produced when one of the scope variables is called this.

evalExpr(expr, focusGraph, focusNode, scope) -> resultNodes

The remainder of this section is non-normative.

6.2 SPARQL Expr Expressions

A node expression that has a value for sh:sparqlExpr is called a SPARQL expr expression with the function name sh:SPARQLExprExpression.

A node in an RDF graph is a well-formed SPARQL expr expression if it is a blank node that has exactly one value for the predicate sh:sparqlExpr and that value is a literal with datatype xsd:string. A well-formed SPARQL expr expression can have at most one value for the property sh:prefixes and this value is an IRI or a blank node.

Let $EXPR$ be the value of sh:eval and $PREFIXES$ be the SPARQL prefixes block resulting from the prefix handling rules using the value of sh:prefixes; then select is defined as the string where $EXPR$ and $PREFIXES$ are inserted as into

$PREFIXES$ SELECT ($EXPR$ AS ?result) WHERE {}

select is a valid SPARQL 1.2 SELECT query.

EVALUATION OF SPARQL EXPR EXPRESSIONS

The output nodes of an SPARQL expr expression are the list resultNodes consisting of exactly the bindings of the (only) variable that is projected from the SELECT clause of the select query as defined above when the query is evaluated against the focus graph. The value of focusNode is pre-bound as the value of the SPARQL variable this. The value of each scope variable is pre-bound as a SPARQL variable with the same name and value. A failure is produced when one of the scope variables is called this.

evalExpr(expr, focusGraph, focusNode, scope) -> resultNodes

The remainder of this section is non-normative.

7. SPARQL-based Inference Rules

SHACL defines an RDF vocabulary to describe shapes - collections of constraints that apply to a set of nodes. Shapes can be associated with nodes using a flexible target mechanism, e.g. for all instances of a class. One focus area of SHACL is data validation. However, the same principles of describing data patterns in shapes can also be exploited for other purposes. SHACL rules build on SHACL to form a light-weight RDF vocabulary for the exchange of rules that can be used to derive inferred RDF triples from existing asserted triples.

The SHACL rules feature defined in this section includes a general framework using the properties such as sh:rule and sh:condition, plus an extension mechanism for specific rule types. This document defines one such rule type: SPARQL rules.

7.1 Examples of SHACL Rules

This section is non-normative.

The following example illustrates a simple use case of a SPARQL rule that applies to all instances of the class ex:Rectangle and computes the values of the ex:area property by multiplying the rectangle's width and height:

An engine that is capable of executing such rules uses the target statements associated with the shapes in the shapes graph to determine which rules need to be executed on which target nodes. For those target nodes that conform to any condition shapes, it executes the provided CONSTRUCT queries to produce the inferred triples. During the execution of the query, the variable this has the current focus node as pre-bound variable.

For the following data graph, the triples below would be produced.

7.2 General Definition of SHACL Rules

The SHACL instances of sh:Rule and its subclass, sh:SPARQLRule, are called SHACL rules. SHACL has a flexible, extensible design in which multiple types of rules can be supported, but this document only defines SPARQL rules. Each rule type is identified by an IRI that is used as their rdf:type. Each rule type also defines execution instructions that can be implemented by rule engines.

Each SHACL rule has at least one rdf:type which is a IRI.

Rules can have multiple types, e.g., to provide instructions that work either in SPARQL or JavaScript, depending on the capabilities of the engine. The creator of such rules needs to make sure that such rules have consistent semantics. Rule R has rule type T if R is a SHACL instance of T.

7.2.1 Shape Rules and Global Rules (sh:rule)

The property sh:rule can be used to link a shape (subject) with a shape rule (object). The subjects of sh:rule triples are IRIs.

SHACL rules can be divided into two categories:

  • A shape rule is a rule that is the object of a sh:rule triple. Shape rules are executed for all target nodes of the shape which is the subject of the sh:rule triple.
  • A global rule is a rule that is not linked to a shape by a sh:rule predicate.

An example of a shape rule was shown above in Example 12.

The following example illustrates a global rule.

7.2.2 Conditions on Shape Rules (sh:condition)

A shape rule may have values for the property sh:condition to specify shapes that the target nodes must conform to before they become focus nodes for the rule.

The values of sh:condition at a rule must be well-formed shapes.

If the value C of sh:condition is a SHACL instance of both sh:NodeShape and rdfs:Class, then the focus nodes must also conform to the constraints of the non-deactivated SHACL superclasses of C that are also SHACL instances of both sh:NodeShape and rdfs:Class. This is similar to how Implicit Class Targets are interpreted during validation.

7.2.3 Deactivated Rules (sh:deactivated)

Rules may be deactivated by setting sh:deactivated to true. Deactivated rules are ignored by the rules engine.

Each rule may have at most one value for the property sh:deactivated. The values of sh:deactivated are either of the xsd:boolean literals true or false.

7.2.4 Grouping of Rules into Strata (sh:stratum)

Rules may be grouped into so-called strata, identified by a numeric value. During execution, a SHACL rules engine will iterate over all rules in the same stratum before moving to the next stratum. Strata with a smaller numeric value will be executed before those with a larger number.

Each rule may have at most one value for the property sh:stratum. The values of sh:stratum at rules are literals with datatype xsd:integer.

If unspecified, then the default stratum of a rule is 0.

An example of sh:stratum to control the execution order of rules is provided in Example 16.

7.2.5 Ordering of Rules (sh:order)

Rules may specify their relative execution order within the same stratum as defined in this section.

Each rule may have at most one value for the property sh:order. The values of sh:order at rules are literals with datatype xsd:decimal or xsd:integer.

If unspecified, then the default execution order is 0. When the rules are executed, within the same stratum, rules with larger order values will be executed after those with smaller values.

7.2.6 Run-once Rules (sh:runOnce)

A SHACL rules engine iterates over the rules, allowing the same rule to be executed multiple times until no further triples are inferred. However, some rules may produce fresh blank nodes with each execution and therefore cause infinite iterations.

Rules may use the property sh:runOnce to instruct a rules engine that the rule is only executed once and before the other rules in the same stratum.

Each rule may have at most one value for the property sh:runOnce. The values of sh:runOnce at rules are literals with datatype xsd:boolean.

A run-once rule is a rule that is executed at most once (per shape, if it is a shape rule). All other rules are called iterating rules. A rule that has true as its value for sh:ruleOnce is a run-once rule.

7.3 Rules Graph

A rules graph is a shapes graph that contains SHACL rules.

The sh:RulesGraph class MAY be used as an rdf:type of the IRI of a graph that typically acts in the role of a rules graph.

The remainder of this section is non-normative.

The graph type classes (sh:DataGraph, sh:ShapesGraph, sh:RulesGraph) represent roles that are not mutually exclusive; a single graph MAY be typed with more than one of these classes. Rules graphs MAY contain sh:rule triples that reference shapes defined in other graphs, allowing rules to be managed independently of shape and ontology definitions.

7.4 The sh:Rules Entailment Regime

SHACL defines the property sh:entailment to link a shapes graph with entailment regimes. The IRI sh:Rules represents the SHACL rules entailment regime. In the following example, the shapes graph indicates to a SHACL validation engine that the SHACL rules inside of the shapes graph need to be executed prior to starting the validation.

<http://example.org/my-shapes>
	a owl:Ontology ;
	sh:entailment sh:Rules .

Following the general policy for SHACL, validation engines that do not support the SHACL rules entailment regime MUST signal a failure if this triple is present. Validation engines that do support the SHACL rules entailment regime execute the rules following the rules execution instructions prior to performing the actual validation.

7.5 General Execution Instructions for SHACL Rules

A SHACL rules engine is a computer procedure that takes as input a data graph and a shapes graph and is capable of adding triples to the data graph. The new triples that are produced by a rules engine are called the inferred triples.

Note that, from a logical perspective, the data graph will be modified if triples get inferred. This means that rules can trigger after other triples have been inferred. However, in cases where the original data should not be modified, implementations may construct a logical data graph that has the original data as one subgraph and a dedicated inferences graph as another subgraph, and where the inferred triples get added to the inferences graph only.

An execution of a rule is the process that produces inferred triples from the rule based on the execution instructions of its rule types. If the rule is a shape rule (i.e., it is linked to at least one shape via sh:rule), then the rule is executed for each target node of each of the linked and non-deactivated shapes that conform to all non-deactivated conditions of the rule. These target nodes become the focus nodes of the executing shape rule.

For a given set of rules in the shapes graph an iteration is a single execution of each individual rule in the order as specified by 7.2.5 Ordering of Rules (sh:order), skipping the rules that are deactivated. Within an iteration, the inferred triples of one rule become immediately visible to the next rule.

The execution of a rule set is defined as follows:

For all strata in the rule set (in ascending order):
	Execute one iteration over all run-once rules in the strata
	do
		Execute one iteration over all iterating rules in the strata
	while the iteration has produced newly inferred triples

If a rules engine is not able to execute a given rule because it does not support any of the rule types of the rule, then it reports a failure.

Rule engines MAY also report a failure after a pre-configured maximum iteration count has been exceeded or a pre-configured maximum number of inferred triples has been produced. This can help as a guard to avoid out-of-memory problems and infinite loops.

At no time are inferred triples visible to the shapes graph, i.e. it is impossible for rules to modify the definitions of rules or shapes.

7.6 Variations of SHACL Rule Implementations

The general execution algorithm described above is intentionally kept generic and offers a lot of flexibility to specific implementations. In particular, the algorithm is non-deterministic in the sense that unless the order of rules is specified explicitly, the results may differ across executions. This is, for example, the case when rules draw conclusions from the absence of triples (negation) yet those triples may be produced by other rules. In this document, the responsibility of producing a predictable ordering and stratification of rules is left to the rule author.

Some SHACL rule implementations MAY implement different algorithms to determine the run-once rules (ignoring sh:runOnce), the rule order (ignoring sh:order), and the stata (ignoring sh:stratum). This can, for example, be used by engines that support controlled subsets of SHACL rules for which it is possible to compute rule dependencies automatically. Another example is a rule engine that automatically prevents infinite loops because rules generate blank nodes. These implementation MAY produce different results from those that only rely on the explicitly given sh:order, sh:runOnce and sh:stratum values.

Some SHACL rule implementations MAY also report additional failures that are not reported by the default algorithm.

Issue 1073: Rules: SPARQL-Full vs SPARQL-RL SPARQLSRLPropose Closing

This would be a good place to cross-reference the ongoing SRL work, if this becomes a SHACL Rules variation.

7.7 SPARQL Rules

This section defines a rule type called SPARQL rules, identified by the IRI sh:SPARQLRule. SPARQL rules have the following properties:

Property Summary and Syntax Rules
sh:construct The SPARQL CONSTRUCT query. SPARQL rules must have exactly one value for the property sh:construct. The values of sh:construct are literals with datatype xsd:string.
sh:prefixes The prefixes to use to turn the sh:construct into a SPARQL query. SPARQL rules may use the property sh:prefixes to declare a dependency on prefixes based on the mechanism defined in Prefix Declarations for SPARQL Queries. This mechanism allows users to abbreviate URIs in the sh:construct strings.
EXECUTION OF SPARQL RULES
Let Q be the SPARQL CONSTRUCT query derived from the values of the properties sh:construct and sh:prefixes of the SPARQL rule in the shapes graph.
Note

Since global SPARQL rules do not use pre-binding, the syntax limitations mentioned in A. Pre-binding of Variables in SPARQL Queries do not apply to them.

Appendix

A. Pre-binding of Variables in SPARQL Queries

Some features of SHACL-SPARQL rely on the concept of pre-binding of variables as defined in this section.

(Feature at Risk) Issue 999: Update pre-binding to align with SPARQL 1.2 SPARQL

This feature is "at risk" and may be changed (not removed) to align with currently ongoing work in the RDF and SPARQL 1.2 work in this area. Originally discussed as Issue 647.

The definition of pre-binding used by SHACL requires the following restrictions on SPARQL queries. SHACL-SPARQL processors MUST report a failure when it is operating on a shapes graph that contains SHACL-SPARQL queries (via sh:ask, sh:construct and sh:select) that are executed with pre-bound variables and violate any of these "MUST" restrictions. Note that the term potentially pre-bound variables includes the variables this, value (for ASK queries), and any variables that represent the parameters of the constraint component that uses the query.

Furthermore, SPARQL queries SHOULD not contain a federated query (SERVICE). Implementations that do not permit SERVICE MUST report a failure as mentioned above. However, it is acknowledged that some SPARQL implementations use the SERVICE keyword as a syntax for specific (typically local) operations and therefore the keyword is not generally disallowed.

DEFINITION: Values Insertion

For solution mapping μ, define Table(μ) to be the multiset formed from μ.

   Table(μ) = { μ }
   Card[μ] = 1

Define the Values Insertion function Replace(X, μ) to replace each occurence Y of a Basic Graph Pattern, Property Path Expression, Graph(Var, pattern) in X with join(Y, Table(μ)).

DEFINITION: Pre-binding of variables

The evaluation of the SPARQL Query Q = (E, DS, QF) with pre-bound variables μ is defined as the evaluation of SPARQL query Q' = (Replace(E, μ), DS, QF).

B. Summary of SHACL Syntax Rules

This section enumerates all normative syntax rules of SHACL. This section is automatically generated from other parts of this spec and hyperlinks are provided back into the prose if the context of the rule in unclear. Nodes that violate these rules in a shapes graph are ill-formed.

Syntax Rule Id Syntax Rule Text
prefix-countPrefix declarations have exactly one value for the property sh:prefix
prefix-datatypeThe values of sh:prefix are literals of datatype xsd:string.
namespace-countPrefix declarations have exactly one value for the property sh:namespace.
namespace-datatypeThe values of sh:namespace are literals of datatype xsd:anyURI or xsd:string.
declare-nodeKindThe values of the property sh:declare are prefix declarations
prefixes-nodeKindThe values of sh:prefixes are either IRIs or blank nodes.
prefixes-duplicatesA SHACL processor collects a set of prefix mappings as the union of all individual prefix mappings that are values of the SPARQL property path sh:prefixes/(^owl:versionIRI?/owl:imports)*/sh:declare of the SPARQL-based constraint or validator. The ^owl:versionIRI? element supports graphs that are imported by owl:versionIRI, navigating from the version IRI to the shapes graph IRI before following further owl:imports. If such a collection of prefix declarations contains multiple different namespaces for the same value of sh:prefix, then the shapes graph is ill-formed.
sparql-nodeKindShapes may have values for the property sh:sparql, and these values are either IRIs or blank nodes.
SPARQLConstraint-select-countSPARQL-based constraints have exactly one value for the property sh:select
SPARQLConstraint-select-datatypeThe value of sh:select is a literal of datatype xsd:string.
select-query-validUsing the prefix handling rules, the value of sh:select is a valid SPARQL 1.2 SELECT query.
select-query-thisThe SPARQL query derived from the value of sh:select projects the variable this in the SELECT clause.
SPARQLConstraint-message-datatypeSPARQL-based constraints may have values for the property sh:message and these are literals with datatype xsd:string, rdf:dirLangString, rdf:langString, or rdf:HTML. There should neither be more than one value for sh:message with the same language tag, nor multiple values with datatype xsd:string.
SPARQLConstraint-deactivated-maxCountSPARQL-based constraints may have at most one value for the property sh:deactivated
SPARQLConstraint-severitySPARQL-based constraints may have at most one value for the property sh:severity and this value is an IRI.
PATH-positionThe only legal use of the variable PATH in the SPARQL queries of SPARQL-based constraints and SELECT-based validators is in the predicate position of a triple pattern.
ConstraintComponentA SPARQL-based constraint component is an IRI that has SHACL type sh:ConstraintComponent in the shapes graph.
Parameter-predicate-countEach parameter declaration has exactly one value for the property sh:path
ParameterAt parameter declarations, the value of sh:path is an IRI.
parameter-name-VARNAMEEvery parameter name is a valid SPARQL VARNAME.
parameter-name-not-inParameter names must not be one of the following: this, path, PATH, value.
parameter-name-uniqueA constraint component where two or more parameter declarations use the same parameter names is ill-formed.
optional-datatypeThe values of sh:optional must be literals with datatype xsd:boolean.
optional-maxCountA parameter declaration can have at most one value for the property sh:optional.
ConstraintComponent-parameterEvery constraint component has at least one non-optional parameter.
Parameter-conformanceShapes that do not conform with the constraints declared for the parameters are ill-formed.
labelTemplate-datatypeThe values of sh:labelTemplate are strings (possibly with language tag)
nodeValidator-classThe values of sh:nodeValidator must be SELECT-based validators.
propertyValidator-classThe values of sh:propertyValidator must be SELECT-based validators.
SPARQLSelectValidator-select-countSELECT-based validators have exactly one value for the property sh:select.
validator-classThe values of sh:validator must be ASK-based validators.
ask-countASK-based validators have exactly one value for the property sh:ask
ask-datatypeThe value of sh:ask must be a literal with datatype xsd:string.
ask-sparqlThe value of sh:ask must be a valid SPARQL ASK query using the aforementioned prefix handling rules.
resultAnnotation-nodeKindThe values of sh:resultAnnotation are called result annotations and are either IRIs or blank nodes
annotationPropertyEach result annotation has exactly one value for the property sh:annotationProperty and this value is an IRI.
annotationVarNameEach result annotation has at most 1 value for the property sh:annotationVarName and this value is literal with datatype xsd:string.
SelectExpression-syntaxA node in an RDF graph is a well-formed select expression if it is a blank node that has exactly one value for the predicate sh:select and this value is a literal with datatype xsd:string.
SelectExpression-syntax-prefixesA well-formed select expression can have at most one value for the property sh:prefixes and this value can only be an IRI or a blank node.
SelectExpression-query-validUsing the prefix handling rules, the value of sh:select is a valid SPARQL 1.2 SELECT query.
SelectExpression-query-output-nodesThe SPARQL query derived from the value of sh:select projects exactly one variable in the SELECT clause.
SPARQLExprExpression-syntax-evalA node in an RDF graph is a well-formed SPARQL expr expression if it is a blank node that has exactly one value for the predicate sh:sparqlExpr and that value is a literal with datatype xsd:string.
SPARQLExprExpression-syntax-prefixesA well-formed SPARQL expr expression can have at most one value for the property sh:prefixes and this value is an IRI or a blank node.
SPARQLExprExpression-templateLet $EXPR$ be the value of sh:eval and $PREFIXES$ be the SPARQL prefixes block resulting from the prefix handling rules using the value of sh:prefixes; then select is defined as the string where $EXPR$ and $PREFIXES$ are inserted as into

$PREFIXES$ SELECT ($EXPR$ AS ?result) WHERE {}

SPARQLExprExpression-query-validselect is a valid SPARQL 1.2 SELECT query.
rule-typeEach SHACL rule has at least one rdf:type which is a IRI.
ruleThe property sh:rule can be used to link a shape (subject) with a shape rule (object). The subjects of sh:rule triples are IRIs.
condition-nodeThe values of sh:condition at a rule must be well-formed shapes.
deactivated-maxCountEach rule may have at most one value for the property sh:deactivated.
deactivated-inThe values of sh:deactivated are either of the xsd:boolean literals true or false.
rule-stratum-maxCountEach rule may have at most one value for the property sh:stratum.
rule-stratum-datatypeThe values of sh:stratum at rules are literals with datatype xsd:integer.
rule-order-maxCountEach rule may have at most one value for the property sh:order.
rule-order-datatypeThe values of sh:order at rules are literals with datatype xsd:decimal or xsd:integer.
run-once-maxCountEach rule may have at most one value for the property sh:runOnce.
run-once-datatypeThe values of sh:runOnce at rules are literals with datatype xsd:boolean.
RulesGraphThe sh:RulesGraph class MAY be used as an rdf:type of the IRI of a graph that typically acts in the role of a rules graph.
construct-countSPARQL rules must have exactly one value for the property sh:construct.
construct-datatypeThe values of sh:construct are literals with datatype xsd:string.
pre-binding-limitations

The definition of pre-binding used by SHACL requires the following restrictions on SPARQL queries. SHACL-SPARQL processors MUST report a failure when it is operating on a shapes graph that contains SHACL-SPARQL queries (via sh:ask, sh:construct and sh:select) that are executed with pre-bound variables and violate any of these "MUST" restrictions. Note that the term potentially pre-bound variables includes the variables this, value (for ASK queries), and any variables that represent the parameters of the constraint component that uses the query.

  • SPARQL queries MUST not contain a MINUS clause
  • SPARQL queries MUST not contain a VALUES clause that mentions any potentially pre-bound variable
  • SPARQL queries MUST not use the syntax form ​​AS ?var for any potentially pre-bound variable

Furthermore, SPARQL queries SHOULD not contain a federated query (SERVICE). Implementations that do not permit SERVICE MUST report a failure as mentioned above. However, it is acknowledged that some SPARQL implementations use the SERVICE keyword as a syntax for specific (typically local) operations and therefore the keyword is not generally disallowed.

C. Potential SPARQL Definitions of SHACL Core Constraint Validators

This section is non-normative.

This appendix uses parts of SPARQL 1.2 in non-normative alternative definitions of the semantics of constraint components and targets from [shacl12-core]. While these may help some implementers, SPARQL is not required for the implementation of the SHACL Core language.

SPARQL variables using the $ marker represent external bindings that are pre-bound or, in the case of $PATH, substituted in the SPARQL query before execution (as explained in 4.3 Validation with SPARQL-based Constraint Components).

C.1 sh:targetClass

The following query expresses a potential definition of class targets in SPARQL. The variable targetClass will be pre-bound to the given value of sh:targetClass. All bindings of the variable this from the solutions become focus nodes.

POTENTIAL DEFINITION IN SPARQL
SELECT DISTINCT ?this    # ?this is the focus node
WHERE {
	?this rdf:type/rdfs:subClassOf* $targetClass .
}

C.2 sh:targetSubjectsOf

The following query expresses a potential definition of subjects-of targets in SPARQL. The variable targetSubjectsOf will be pre-bound to the given value of sh:targetSubjectsOf. All bindings of the variable this from the solutions become focus nodes.

POTENTIAL DEFINITION IN SPARQL
SELECT DISTINCT ?this    # ?this is the focus node
WHERE {
	?this $targetSubjectsOf ?any .
}

C.3 sh:targetObjectsOf

The following query expresses a potential definition of objects-of targets in SPARQL. The variable targetObjectsOf will be pre-bound to the given value of sh:targetObjectsOf. All bindings of the variable this from the solutions become focus nodes.

POTENTIAL DEFINITION IN SPARQL
SELECT DISTINCT ?this    # ?this is the focus node
WHERE {
	?any $targetObjectsOf ?this .
}

C.4 sh:class

The following query expresses a potential SPARQL-based validator for sh:class.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {
	$value rdf:type/rdfs:subClassOf* $class .
}

C.5 sh:nodeKind

The following query expresses a potential SPARQL-based validator for sh:nodeKind.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {
	FILTER ((isIRI($value) && $nodeKind IN ( sh:IRI, sh:BlankNodeOrIRI, sh:IRIOrLiteral ) ) ||
		(isLiteral($value) && $nodeKind IN ( sh:Literal, sh:BlankNodeOrLiteral, sh:IRIOrLiteral ) ) ||
		(isBlank($value)   && $nodeKind IN ( sh:BlankNode, sh:BlankNodeOrIRI, sh:BlankNodeOrLiteral ) )) .
}

C.6 sh:minExclusive (etc)

The following query expresses a potential SPARQL-based validator for sh:minExclusive. The SPARQL expression produces an error if the value node cannot be compared to the specified range, for example when someone compares a string with an integer. If the comparison cannot be performed, then there is a validation result. This is different from, say, a plain SPARQL query, in which such errors would silently not lead to any results.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {
	FILTER ($minExclusive < $value)
}

Similar definitions are possible for:

C.7 sh:minLength

The following query expresses a potential SPARQL-based validator for sh:minLength.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {
	FILTER (STRLEN(str($value)) >= $minLength) .
}

C.8 sh:maxLength

The following query expresses a potential SPARQL-based validator for sh:maxLength.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {
	FILTER (STRLEN(str($value)) <= $maxLength) .
}

C.9 sh:pattern

The following query expresses a potential SPARQL-based validator for sh:pattern.

POTENTIAL DEFINITION IN SPARQL (Must evaluate to true for each value node $value)
ASK {
	FILTER (!isBlank($value) && IF(bound($flags), regex(str($value), $pattern, $flags), regex(str($value), $pattern)))
}

C.10 sh:disjoint

The following query expresses a potential SPARQL-based validator for sh:disjoint.

POTENTIAL DEFINITION IN SPARQL (Must return no results for the given $PATH)
SELECT DISTINCT $this ?value
WHERE {
	$this $PATH ?value .
	$this $disjoint ?value .
}

C.11 sh:lessThan

The following query expresses a potential SPARQL-based validator for sh:lessThan.

POTENTIAL DEFINITION IN SPARQL (Must return no results for the given $PATH)
SELECT $this ?value
WHERE {
	$this $PATH ?value .
	$this $lessThan ?otherValue .
	BIND (?value < ?otherValue AS ?result) .
	FILTER (!bound(?result) || !(?result)) .
}

C.12 sh:lessThanOrEquals

The following query expresses a potential SPARQL-based validator for sh:lessThanOrEquals.

POTENTIAL DEFINITION IN SPARQL (Must return no results for the given $PATH)
SELECT $this ?value
WHERE {
	$this $PATH ?value .
	$this $lessThanOrEquals ?otherValue .
	BIND (?value <= ?otherValue AS ?result) .
	FILTER (!bound(?result) || !(?result)) .
}

D. Security and Privacy Considerations

This section is non-normative.

Note that SPARQL key words such as GRAPH and FROM may provide access to graphs other than the active data graph in the dataset. A SHACL-SPARQL engine should ensure that the SPARQL engine does not provide access to named graphs which the user who has triggered the validation is not permitted to access.

Security considerations of SHACL-SPARQL include all the security considerations of SPARQL, SPARQL Federated Query (SERVICE) and SHACL Core.

E. Acknowledgements

This section is non-normative.

Original SHACL core specifications were produced by the RDF Data Shapes Working Group. See the Core specification's Acknowledgements section and the Advanced Features specification's Acknowledgements section.

F. Changes between the original SHACL specifications and SHACL 1.2 SPARQL

This section is non-normative.

G. References

G.1 Normative references

[owl2-syntax]
OWL 2 Web Ontology Language Structural Specification and Functional-Style Syntax (Second Edition). Boris Motik; Peter Patel-Schneider; Bijan Parsia. W3C. 11 December 2012. W3C Recommendation. URL: https://www.w3.org/TR/owl2-syntax/
[rdf12-concepts]
RDF 1.2 Concepts and Abstract Data Model. Andy Seaborne; Gregg Kellogg; Olaf Hartig; Pierre-Antoine Champin. W3C. 7 April 2026. W3C Candidate Recommendation. URL: https://www.w3.org/TR/rdf12-concepts/
[rdf12-turtle]
RDF 1.2 Turtle. Gregg Kellogg; Andy Seaborne; Dominik Tomaszuk. W3C. 23 July 2026. W3C Working Draft. URL: https://www.w3.org/TR/rdf12-turtle/
[REC-xml-names]
Namespaces in XML 1.0 (Third Edition). Tim Bray; Dave Hollander; Andrew Layman; Richard Tobin; Henry Thompson et al. W3C. 8 December 2009. W3C Recommendation. URL: https://www.w3.org/TR/xml-names/
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL: https://www.rfc-editor.org/info/rfc2119/
[RFC8174]
Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL: https://www.rfc-editor.org/info/rfc8174/
[shacl12-core]
SHACL 1.2 Core. Holger Knublauch; Thomas Bergwinkl; Yousouf Taghzouti; Jesse Wright. W3C. 23 July 2026. W3C Working Draft. URL: https://www.w3.org/TR/shacl12-core/
[sparql12-query]
SPARQL 1.2 Query Language. Olaf Hartig; Andy Seaborne; Ruben Taelman; Gregory Williams; Thomas Pellissier Tanon. W3C. 25 June 2026. W3C Working Draft. URL: https://www.w3.org/TR/sparql12-query/
[vc-data-model]
Verifiable Credentials Data Model v2.0. Ivan Herman; Michael Jones; Manu Sporny; Ted Thibodeau Jr; Gabe Cohen. W3C. 15 May 2025. W3C Recommendation. URL: https://www.w3.org/TR/vc-data-model-2.0/

G.2 Informative references

[sparql12-federated-query]
SPARQL 1.2 Federated Query. Ruben Taelman; Gregory Williams. W3C. 23 April 2026. W3C Working Draft. URL: https://www.w3.org/TR/sparql12-federated-query/