SPARQL
Updated: May 22, 2026Categories: Query
Printed from:
SPARQL Cheatsheet: Querying Linked Data and Knowledge Graphs
1. Connection and Basic Setup
SPARQL Endpoints
- HTTP-based interfaces for querying RDF data (SPARQL 1.1 Protocol)
- Common implementations:
- Apache Jena Fuseki - GraphDB (Ontotext) - Virtuoso (OpenLink) - Blazegraph (archived; consider alternatives) - Stardog - Oxigraph - Amazon Neptune - Qlever
Tools and Libraries
- Query Clients:
- Apache Jena ARQ - RDFLib (Python) - rdflib.js / Comunica (JavaScript) - dotNetRDF (.NET) - rdf4j (Java) - sparql-client / SPARQLWrapper (Python) - Visualization:
- YASGUI (query/result UI) - LodLive - WebVOWL - Gephi - Graphviz
2. RDF Data Model Basics
Core Concepts
- Triple: Subject - Predicate - Object
- Quad: Triple + named graph (RDF 1.1 datasets)
- IRI (Internationalized Resource Identifier): Unicode-aware identifier (supersedes URI in RDF 1.1)
- Literal: Primitive values with a datatype IRI; optional language tag for
rdf:langString - Blank Node: Anonymous resource scoped to a document/store
- RDF-star (RDF 1.2): Quoted triples for statement-level annotations (
<< :s :p :o >>)
Example Triples (Turtle)
turtle
12345678@prefix : <http://example.org/> . @prefix foaf: <http://xmlns.com/foaf/0.1/> . @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . :john foaf:name "John Doe" ; foaf:age "30"^^xsd:integer ; foaf:knows :jane .
3. Basic SPARQL Syntax and Structure
Query Types
SELECT: Retrieve variable bindingsCONSTRUCT: Build a new RDF graphASK: Boolean queryDESCRIBE: Retrieve a resource description (implementation-defined shape)
Minimal Query Structure
sparql
123456789PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?name ?age WHERE { ?person foaf:name ?name ; foaf:age ?age . }
4. SELECT Queries and Result Formats
Basic SELECT
sparql
123456SELECT ?subject ?predicate ?object WHERE { ?subject ?predicate ?object . } LIMIT 10
Standard Result Formats
- SPARQL Results JSON (
application/sparql-results+json) - SPARQL Results XML (
application/sparql-results+xml) - CSV (
text/csv) - TSV (
text/tab-separated-values) - For
CONSTRUCT/DESCRIBE: Turtle, JSON-LD, N-Triples, Trig, N-Quads
Modifiers
sparql
1234SELECT DISTINCT ?name # Unique results SELECT REDUCED ?name # Permits duplicate elimination SELECT ?name (COUNT(?friend) AS ?friendCount) # Aggregation with projection
5. Graph Patterns and Triple Patterns
Simple Pattern
sparql
123?person a foaf:Person ; # 'a' is shorthand for rdf:type foaf:name ?name .
Multiple Patterns and Property Paths
sparql
123456789101112# Joined patterns ?person foaf:name ?name ; foaf:knows ?friend . ?friend foaf:based_near/schema:addressCountry "CA" . # Property paths (SPARQL 1.1) ?person foaf:knows+ ?reachable . # one or more hops ?person foaf:knows* ?selfOrReachable . # zero or more ?s rdfs:subClassOf*/rdf:type ?class . # sequence ?s (foaf:knows|foaf:colleague) ?other . # alternative ?s !rdf:type ?o . # negated property set
Named Graphs
sparql
1234567SELECT ?s ?p ?o FROM <http://example.org/g1> FROM NAMED <http://example.org/g2> WHERE { GRAPH ?g { ?s ?p ?o } }
6. Filtering and Matching
FILTER
sparql
123456789FILTER (?age > 25) FILTER (REGEX(?name, "^John", "i")) FILTER (BOUND(?email)) FILTER (LANG(?label) = "en") FILTER (DATATYPE(?v) = xsd:integer) FILTER (?date >= "2025-01-01"^^xsd:date) FILTER NOT EXISTS { ?person foaf:knows ?anyone } FILTER EXISTS { ?person foaf:mbox ?mbox }
Comparison and Logical Operators
=,!=,<,>,<=,>=,IN,NOT IN&&(AND),||(OR),!(NOT)
Common Functions (SPARQL 1.1)
- String:
STR,STRLEN,SUBSTR,UCASE,LCASE,CONCAT,CONTAINS,STRSTARTS,STRENDS,REPLACE,REGEX - Numeric:
ABS,CEIL,FLOOR,ROUND,RAND - Date/Time:
NOW,YEAR,MONTH,DAY,HOURS,MINUTES,SECONDS,TIMEZONE,TZ - Hash:
MD5,SHA1,SHA256,SHA384,SHA512 - Term:
isIRI,isLiteral,isBlank,IRI,BNODE,UUID,STRUUID,COALESCE,IF
7. Optional, Union, and Minus Patterns
OPTIONAL
sparql
123?person foaf:name ?name . OPTIONAL { ?person foaf:mbox ?email }
UNION
sparql
1234{ ?person a foaf:Person } UNION { ?person a schema:Person }
MINUS
sparql
123?person a foaf:Person . MINUS { ?person foaf:knows ?anyone }
VALUES (inline data)
sparql
12345VALUES (?country ?code) { ("Canada" "CA") ("United States" "US") }
8. Aggregation and Grouping
Aggregation Example
sparql
12345678SELECT ?country (COUNT(?person) AS ?population) WHERE { ?person schema:addressCountry ?country . } GROUP BY ?country HAVING (COUNT(?person) > 1000) ORDER BY DESC(?population)
Supported Aggregates
COUNT,SUM,AVG,MIN,MAX,SAMPLE,GROUP_CONCAT
sparql
1234SELECT ?person (GROUP_CONCAT(?skill; SEPARATOR=", ") AS ?skills) WHERE { ?person ex:hasSkill ?skill } GROUP BY ?person
9. Subqueries, BIND, and Nested Queries
Subquery Example
sparql
123456789101112SELECT ?name ?friendCount WHERE { { SELECT ?person (COUNT(?friend) AS ?friendCount) WHERE { ?person foaf:knows ?friend } GROUP BY ?person } ?person foaf:name ?name . } ORDER BY DESC(?friendCount) LIMIT 20
BIND
sparql
123?person foaf:givenName ?g ; foaf:familyName ?f . BIND (CONCAT(?g, " ", ?f) AS ?fullName)
10. Data Modification (SPARQL 1.1 Update)
INSERT DATA / DELETE DATA
sparql
123456789101112PREFIX ex: <http://example.org/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> INSERT DATA { ex:john foaf:name "John Doe" ; foaf:age 30 . } DELETE DATA { ex:john foaf:age 30 . }
DELETE/INSERT WHERE (pattern-based)
sparql
1234567DELETE { ?p foaf:age ?old } INSERT { ?p foaf:age ?new } WHERE { ?p foaf:age ?old . BIND (?old + 1 AS ?new) }
Graph Management
sparql
1234567CREATE GRAPH <http://example.org/g1> ; COPY <http://example.org/g1> TO <http://example.org/g2> ; MOVE <http://example.org/g2> TO <http://example.org/g3> ; ADD <http://example.org/g3> TO <http://example.org/g1> ; CLEAR GRAPH <http://example.org/g1> ; DROP GRAPH <http://example.org/g1> ;
11. Federation and Remote Querying
SERVICE Keyword
sparql
12345678SELECT ?name ?remoteData WHERE { ?person foaf:name ?name . SERVICE <https://remote-endpoint.org/sparql> { ?person ex:additionalInfo ?remoteData . } }
SERVICE SILENT (tolerate endpoint failures)
sparql
1234SERVICE SILENT <https://example.org/sparql> { ?s ?p ?o . }
12. Common Prefixes and Vocabularies
sparql
12345678910111213PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX schema:<http://schema.org/> PREFIX dcterms:<http://purl.org/dc/terms/> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX sh: <http://www.w3.org/ns/shacl#> PREFIX wd: <http://www.wikidata.org/entity/> PREFIX wdt: <http://www.wikidata.org/prop/direct/> PREFIX geo: <http://www.opengis.net/ont/geosparql#>
Prefer dcterms: over the legacy dc: namespace for new data.
13. Performance Optimization
Best Practices
- Use
LIMITandOFFSET(with stableORDER BYfor pagination) - Constrain by type and selective predicates early
- Replace expensive
OPTIONAL/FILTER NOT EXISTSwithMINUSwhen semantics match - Prefer property paths over recursive joins, but watch for
*/+cost - Use
VALUESto push selective bindings into the query - Avoid unbounded
REGEX; preferSTRSTARTSor full-text indexes - Index your RDF store; enable text/geo indexes where applicable
- Materialize frequently used inferences instead of relying on runtime reasoning
Paginated Example
sparql
123456SELECT ?person ?name WHERE { ?person foaf:name ?name } ORDER BY ?person LIMIT 100 OFFSET 200
14. Best Practices for Semantic Web Applications
Query Design
- Keep queries focused and small; compose via subqueries
- Use canonical prefixes and IRIs
- Filter by
rdf:typebefore traversing predicates - Cache results and reuse parameterized queries
- Profile with EXPLAIN plans where the engine supports them
Validation
- Validate data with SHACL (W3C Recommendation) or ShEx
- Apply OWL reasoning only where needed; prefer OWL 2 RL/QL/EL profiles for scalability
- Use strict datatype literals (
xsd:integer,xsd:dateTime, etc.)
Security
- Treat SPARQL endpoints as you would SQL: parameterize, escape literals, enforce ACLs
- Disable or restrict
SERVICEandLOADon public endpoints - Use HTTPS and authentication for update endpoints
Tools and Frameworks
- Apache Jena / Fuseki
- RDF4J
- RDFLib (Python)
- Stardog
- GraphDB
- Virtuoso
- Oxigraph
- Comunica (federated query in JS)
Pro Tips:
- Prefer SPARQL 1.1 features (property paths,
BIND,VALUES, subqueries, aggregates) over manual workarounds - Watch for RDF 1.1 changes: plain literals are
xsd:string; language-tagged literals arerdf:langString - Track RDF-star / SPARQL-star (RDF 1.2) support if you need statement-level metadata
- Validate ontologies and shapes in CI
- Stay current with the W3C RDF and SPARQL Working Groups
Learning Resources:
- W3C SPARQL 1.1 Query and Update Recommendations
- W3C RDF 1.1 Primer and Concepts
- SHACL Specification (W3C)
- Apache Jena and RDF4J documentation
- Wikidata Query Service tutorials
Continue Learning
Discover more cheatsheets to boost your productivity