SPARQL: The Standard Query Language for RDF Graphs
#sparql#rdf#semantic-web#knowledge-graph#query-language
Contents
Assume an MDR (managed detection and response) service keeps its asset and alert data as RDF.
Rows of the asset table assets(id, hostname, criticality), the alert table alerts(id, asset_id, title, severity_id) and the network link table between assets links(src_id, dst_id) are expressed as the following triples.
@prefix ex: <http://example.org/> .
@prefix asset: <http://example.org/asset/> .
@prefix alert: <http://example.org/alert/> .
# Assets 7 and 9 have High criticality, 8 is Low, 10 is not classified yet
asset:7 a ex:Asset ; ex:hostname "web-01" ; ex:criticality "High" .
asset:8 a ex:Asset ; ex:hostname "dev-02" ; ex:criticality "Low" .
asset:9 a ex:Asset ; ex:hostname "db-01" ; ex:criticality "High" .
asset:10 a ex:Asset ; ex:hostname "lab-03" .
# Each alert (detection finding) with its asset, title and severity (severity_id)
alert:1001 a ex:DetectionFinding ; ex:onAsset asset:7 ; ex:title "ssh-bruteforce" ; ex:severityId 4 .
alert:1002 a ex:DetectionFinding ; ex:onAsset asset:8 ; ex:title "port-scan" ; ex:severityId 2 .
alert:1003 a ex:DetectionFinding ; ex:onAsset asset:9 ; ex:title "sql-injection" ; ex:severityId 5 .
alert:1004 a ex:DetectionFinding ; ex:onAsset asset:7 ; ex:title "malware-beacon" ; ex:severityId 3 .
# Network links between assets: dev-02 -> web-01 -> db-01
asset:8 ex:connectsTo asset:7 .
asset:7 ex:connectsTo asset:9 .
OCSF (Open Cybersecurity Schema Framework) is an open schema that defines field names and values for security events. The alert data in this post follows finding_info.title and severity_id of the OCSF Detection Finding class, and the asset data follows hostname and criticality of resource_details.
Alerts raised on assets with High criticality are queried as follows.
PREFIX ex: <http://example.org/>
SELECT ?finding ?severity WHERE {
?asset a ex:Asset ; ex:criticality "High" .
?finding ex:onAsset ?asset ; ex:severityId ?severity .
}
| ?finding | ?severity |
|---|---|
| alert:1001 | 4 |
| alert:1003 | 5 |
| alert:1004 | 3 |
The result is the three alerts raised on assets 7 and 9, which have High criticality, and the severity of each.
The query does not name tables or join columns; it describes the shape of the graph to find with triple patterns.
SPARQL is the W3C standard query language for RDF graphs.
A lookup like this is not very different from SQL, but the difference shows when a query follows relationships over several steps or asks without knowing which relationships exist.
1. Background
After RDF was standardized, a number of graph query languages appeared.
Each had its own syntax and semantics, so a standard was needed, and RDQL from HP Labs became the starting point of the W3C design.
| Version | Status | Contents |
|---|---|---|
| SPARQL 1.0 | W3C Recommendation, January 2008 | Query language, HTTP protocol, XML results format |
| SPARQL 1.1 | W3C Recommendation, March 2013 | 11 documents including aggregates, subqueries, negation, property paths, Update, Federated Query, and JSON, CSV and TSV results formats |
| SPARQL 1.2 | Working Draft (as of October 2026) | Syntax for RDF 1.2 triple terms and more |
Engines and tools today are built against SPARQL 1.1.
SPARQL 1.2 is not a Recommendation yet and may change.
2. Basic syntax
The introductory query retrieves alerts raised on assets with High criticality and the severity of each alert.
A query has three parts: PREFIX, SELECT and WHERE.
PREFIX ex: <http://example.org/> # prefix definition
SELECT ?finding ?severity # variables to return
WHERE { # graph pattern to match
?asset a ex:Asset ; ex:criticality "High" .
?finding ex:onAsset ?asset ; ex:severityId ?severity .
}
- PREFIX: defines a prefix that shortens long IRIs.
ex:Assetstands for<http://example.org/Asset>. - SELECT: picks the variables to return. Variables start with
?. - WHERE: describes the shape of the graph to find with triple patterns.
The two conditions in WHERE mean the following.
- First condition: find assets (
ex:Asset) whose criticality is “High” and bind them to?asset. - Second condition: find alerts raised on
?asset, bind them to?finding, and bind each alert’s severity to?severity.
Binding means a value from the data is assigned to a variable.
The two conditions are connected through the same variable ?asset.
The engine finds the parts of the data graph that match the query pattern; this is called graph pattern matching.
The introductory query produces its result in the three steps below.
The Graph Patterns section of the SPARQL 1.1 specification opens with "SPARQL is based around graph pattern matching".
The second condition does not look at every alert; it only finds alerts raised on the High assets (assets 7 and 9) found by the first condition.
That is why alert 1002, raised on asset 8 with Low criticality, is not in the result.
alert:1001 is the prefixed short form of http://example.org/alert/1001. It refers to alert 1001 in the data above.
3. OPTIONAL, UNION, FILTER
3.1 OPTIONAL
Every pattern in WHERE has to match for a row to be in the result.
To also include assets with no matching alert, wrap the alert pattern in OPTIONAL.
It works much like a LEFT OUTER JOIN in SQL.
SELECT ?host ?finding WHERE {
?asset a ex:Asset ; ex:hostname ?host .
OPTIONAL { ?finding ex:onAsset ?asset }
}
| ?host | ?finding |
|---|---|
| web-01 | alert:1001 |
| web-01 | alert:1004 |
| dev-02 | alert:1002 |
| db-01 | alert:1003 |
| lab-03 |
Without OPTIONAL, lab-03, which has no alert, is excluded from the result.
In a row where the OPTIONAL pattern does not match, ?finding has no value and is unbound.
Unbound means no value is bound to the variable at all. It shows as an empty cell in a result table, and in JSON results the variable is left out of that row entirely. It looks like SQL NULL, but NULL is a value called NULL, while unbound means there is no value.
3.2 UNION
UNION combines the results of two patterns.
Querying alerts raised on High assets together with alerts of severity 4 (High) or higher looks like this.
SELECT ?finding WHERE {
# first block: alerts raised on High assets
{ ?finding ex:onAsset ?asset . ?asset ex:criticality "High" }
UNION
# second block: alerts with severity 4 (High) or higher
{ ?finding ex:severityId ?severity . FILTER (?severity >= 4) }
}
The engine runs each block separately and then merges the two results.
The first block returns alert:1001, 1003 and 1004, and the second block returns alert:1001 and 1003.
alert:1001 and alert:1003 satisfy both blocks, so they appear twice in the result.
SPARQL does not remove duplicates by default, so use DISTINCT to see each result once.
SELECT DISTINCT ?finding WHERE {
{ ?finding ex:onAsset ?asset . ?asset ex:criticality "High" }
UNION
{ ?finding ex:severityId ?severity . FILTER (?severity >= 4) }
}
3.3 FILTER
FILTER returns only the results for which the condition is true.
Adding FILTER (?severity >= 4) to the introductory query excludes alert:1004 (severity 3) and leaves alert:1001 and alert:1003.
SELECT ?finding ?severity WHERE {
?asset a ex:Asset ; ex:criticality "High" .
?finding ex:onAsset ?asset ; ex:severityId ?severity .
FILTER (?severity >= 4)
}
| ?finding | ?severity |
|---|---|
| alert:1001 | 4 |
| alert:1003 | 5 |
Where FILTER sits matters when it is used with OPTIONAL.
Inside OPTIONAL it is a condition that selects the OPTIONAL match; outside OPTIONAL it filters the whole result after OPTIONAL is done.
# inside: attach only alerts with severity 4 or higher, and keep assets without such alerts
OPTIONAL { ?finding ex:onAsset ?asset ; ex:severityId ?severity . FILTER (?severity >= 4) }
# outside: attach all alerts, then drop results whose severity is not 4 or higher
OPTIONAL { ?finding ex:onAsset ?asset ; ex:severityId ?severity . }
FILTER (?severity >= 4)
Asset 10, whose ?severity is unbound, has no value to compare and does not pass the outer FILTER.
Use BOUND(?finding) to check whether a value is present.
4. Where it differs from SQL
For lookups that join a few tables with a fixed schema, SQL is enough.
Graph queries have the edge in the three cases below.
4.1 Following relationships over several steps
Say a port-scan alert (alert:1002) is raised on dev-02 (asset:8), an asset with Low criticality.
To find the assets reachable from it over network links, you cannot know in advance how many links to follow.
SPARQL writes this kind of query in one line with a property path.
SELECT ?target ?host WHERE {
alert:1002 ex:onAsset ?start .
?start ex:connectsTo+ ?target . # follow links one or more times
?target ex:hostname ?host .
}
| ?target | ?host |
|---|---|
| asset:7 | web-01 |
| asset:9 | db-01 |
+ means one or more steps and * means zero or more.
/ connects predicates in sequence, and ^ follows a link in reverse.
Writing the same query in SQL requires a recursive CTE (WITH RECURSIVE).
4.2 When you do not know which relationships exist
SPARQL can put a variable in the predicate position too.
The query below retrieves every fact the graph holds about asset 7.
SELECT ?p ?o WHERE { asset:7 ?p ?o }
| ?p | ?o |
|---|---|
| rdf:type | ex:Asset |
| ex:hostname | “web-01” |
| ex:criticality | “High” |
| ex:connectsTo | asset:9 |
Switching to ?s ?p asset:7 finds, in reverse, every alert and link that points to asset 7.
In SQL you have to know the column names to write a query, and each table that references asset 7 has to be queried separately.
4.3 Combining data from different sources
Data from different sources, such as EDR alerts, a cloud asset inventory and account data, merges into one graph when it uses the same asset IRI, even if each source is structured differently.
# triple from the cloud asset inventory
asset:7 ex:cloudRegion "ap-northeast-2" .
# triple from account data
asset:7 ex:ownedBy <http://example.org/user/u-100> .
A new relationship only needs new triples; no table schema changes.
Mapping each source so that the same thing gets the same IRI is still separate work.
5. Sorting, deduplication and aggregation
- ORDER BY: sorts the result.
ORDER BY DESC(?severity)puts the highest severity first. - LIMIT, OFFSET: set the number of results and where they start.
- DISTINCT: keeps each identical result once.
- GROUP BY and aggregates: since SPARQL 1.1, aggregates such as
COUNT,SUM,MIN,MAXandAVGare available.
Querying the two alerts with the highest severity looks like this.
SELECT ?finding ?severity WHERE {
?finding ex:severityId ?severity .
}
ORDER BY DESC(?severity)
LIMIT 2
| ?finding | ?severity |
|---|---|
| alert:1003 | 5 |
| alert:1001 | 4 |
Counting alerts per High asset and sorting by count looks like this.
SELECT ?asset (COUNT(?finding) AS ?findings) WHERE {
?asset a ex:Asset ; ex:criticality "High" .
?finding ex:onAsset ?asset .
}
GROUP BY ?asset
ORDER BY DESC(?findings)
| ?asset | ?findings |
|---|---|
| asset:7 | 2 |
| asset:9 | 1 |
6. Query forms and endpoints
6.1 Four query forms and Update
| Query form | Returns | MDR example |
|---|---|---|
| SELECT | A table of variables and values | List of alerts on High assets |
| ASK | true or false | Is there a severity 5 alert on a High asset? |
| CONSTRUCT | An RDF graph built from a template | A graph of only the hostname triples of High assets |
| DESCRIBE | An RDF graph describing a resource | DESCRIBE asset:7 |
The specification does not define which triples DESCRIBE returns; that is up to the implementation.
Requests that change data are defined by a separate specification, SPARQL 1.1 Update.
PREFIX ex: <http://example.org/>
PREFIX asset: <http://example.org/asset/>
PREFIX alert: <http://example.org/alert/>
# add one new alert
INSERT DATA {
alert:1005 a ex:DetectionFinding ; ex:onAsset asset:10 ; ex:severityId 2 .
}
6.2 SPARQL Protocol
An HTTP service that accepts SPARQL queries is called a SPARQL endpoint.
SPARQL 1.1 Protocol says a query is sent as the query parameter of a GET, as a URL-encoded POST, or as a POST whose body is application/sparql-query.
Updates are sent only with POST.
# the endpoint address is an example
curl -G https://sparql.example.org/query \
-H 'Accept: application/sparql-results+json' \
--data-urlencode 'query=SELECT ?finding WHERE { ?finding a <http://example.org/DetectionFinding> } LIMIT 1'
SELECT results can be received in the SPARQL 1.1 Query Results JSON Format.
The variable list goes in head and the rows in results.bindings, and each value carries whether it is an IRI or a literal along with its datatype.
{
"head": { "vars": ["finding"] },
"results": {
"bindings": [
{ "finding": { "type": "uri", "value": "http://example.org/alert/1001" } }
]
}
}
7. Query processing
A SPARQL engine processes query text in this order.
- Parsing: checks the syntax of the query text and expands prefixes into full IRIs.
- Algebra tree: turns the query into a tree of operators. Triple patterns written side by side in braces become one BGP (basic graph pattern), and OPTIONAL becomes LeftJoin, UNION becomes Union, and FILTER becomes the Filter operator. The SPARQL 1.1 specification defines the meaning of a query in terms of this algebra tree.
- Optimization: rewrites the tree to lower execution cost without changing the result. A typical example is estimating the number of results (cardinality) and ordering joins so that patterns with fewer results run first. The exact method differs by engine.
- Execution: how the query runs depends on where the data is stored.
- Serialization: SELECT and ASK results are returned as JSON, XML, CSV or TSV, and CONSTRUCT and DESCRIBE results as an RDF format such as Turtle.
- Triple store: an engine that stores RDF directly finds matching triples for each triple pattern in its indexes and joins the matches on variables.
- Virtualization: an engine that leaves the source database as it is uses a mapping to translate the algebra tree to SQL, and converts the rows the source database returns back into RDF values. The introductory query becomes a join of
assetsandalertswith the conditioncriticality = 'High'.
The difference between the two approaches is covered in more detail in Materialization and Virtualization: Two Ways to Query Source Data Through an Ontology.
References
- W3C SPARQL 1.1 Overview
- W3C SPARQL 1.1 Query Language - Query Forms, SPARQL Algebra, Property Paths
- PostgreSQL WITH Queries (Common Table Expressions)
- W3C SPARQL 1.1 Update
- W3C SPARQL 1.1 Protocol
- W3C SPARQL 1.1 Query Results JSON Format
- W3C SPARQL Query Language for RDF (1.0)
- W3C SPARQL 1.2 Query Language (Working Draft)
- W3C RDQL - A Query Language for RDF (Member Submission)
- W3C RDF Data Access Use Cases and Requirements
- OCSF Schema