SPARQL: The Standard Query Language for RDF Graphs

architecture12 min한국어

#sparql#rdf#semantic-web#knowledge-graph#query-language

Assume an MDR (managed detection and response) service keeps its asset and alert data as RDF.

analyst tools AI agents applications query: SPARQL Protocol (HTTP) results: JSON, XML SPARQL engine (endpoint) parsing optimization execution triple store stores RDF directly relational DB mapping to SQL other endpoints federation with SERVICE
Clients send queries with a standard protocol and receive results in a standard format.

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:10014
alert:10035
alert:10043

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.

VersionStatusContents
SPARQL 1.0W3C Recommendation, January 2008Query language, HTTP protocol, XML results format
SPARQL 1.1W3C Recommendation, March 201311 documents including aggregates, subqueries, negation, property paths, Update, Federated Query, and JSON, CSV and TSV results formats
SPARQL 1.2Working 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:Asset stands 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".

Step 1: find High assets with the first condition ?asset a ex:Asset ; ex:criticality "High" asset:7 High asset:8 Low, excluded asset:9 High asset:10 unrated, excluded Step 2: find alerts raised on ?asset with the second condition ?finding ex:onAsset ?asset ; ex:severityId ?severity ?asset = asset:7 ?asset = asset:9 alert:1001 severity 4 alert:1004 severity 3 alert:1003 severity 5 Step 3: return only the variables SELECT picks ?finding ?asset ?severity ?finding ?severity alert:1001 asset:7 4 alert:1001 4 alert:1004 asset:7 3 alert:1004 3 alert:1003 asset:9 5 alert:1003 5 SELECT ?asset, not in SELECT, is dropped
The ?asset value bound in step 1 is used as a condition in step 2, so step 2 only finds alerts raised on High assets.

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-01alert:1001
web-01alert:1004
dev-02alert:1002
db-01alert:1003
lab-03
Step 1: find assets with the required pattern ?asset a ex:Asset ; ex:hostname ?host asset:7 web-01 asset:8 dev-02 asset:9 db-01 asset:10 lab-03 Step 2: find alerts for each asset with the OPTIONAL pattern OPTIONAL { ?finding ex:onAsset ?asset } asset:7 alert:1001 alert:1004 asset:8 alert:1002 asset:9 alert:1003 asset:10 no matching alert, ?finding unbound
Every asset found by the required pattern stays in the result. asset:10 has no alert and stays with ?finding unbound.

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) }
}
Step 1: run each block Step 2: UNION merge Step 3: DISTINCT first block alert:1001 alert:1003 alert:1004 second block alert:1001 alert:1003 alert:1001 alert:1003 alert:1004 alert:1001 duplicate alert:1003 duplicate alert:1001 alert:1003 alert:1004 DISTINCT
UNION merges the results of both blocks as they are, so alert:1001 and alert:1003 are returned twice. DISTINCT keeps each once.

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:10014
alert:10035

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)
FILTER inside OPTIONAL FILTER outside OPTIONAL ?asset ?finding ?severity ?asset ?finding ?severity asset:7 alert:1001 4 asset:8 (none) (none) asset:9 alert:1003 5 asset:10 (none) (none) asset:7 alert:1001 4 asset:7 alert:1004 3 removed asset:8 alert:1002 2 removed asset:9 alert:1003 5 asset:10 (none) (none) removed assets 8 and 10 stay without alerts assets 8 and 10 disappear
With FILTER inside OPTIONAL, assets 8 and 10 stay without alerts. With FILTER outside, the whole result is filtered and assets 8 and 10 disappear.

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:7web-01
asset:9db-01
alert:1002 port-scan asset:8 dev-02, Low asset:7 web-01, High asset:9 db-01, High ex:onAsset ex:connectsTo ex:connectsTo step 1 step 2 assets reached with ex:connectsTo+
connectsTo+ follows connections one or more steps. The query reaches both asset:7 and asset:9 without fixing the number of steps.

+ 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:typeex:Asset
ex:hostname“web-01”
ex:criticality“High”
ex:connectsToasset: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, MAX and AVG are 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:10035
alert:10014

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:72
asset:91

6. Query forms and endpoints

6.1 Four query forms and Update

Query formReturnsMDR example
SELECTA table of variables and valuesList of alerts on High assets
ASKtrue or falseIs there a severity 5 alert on a High asset?
CONSTRUCTAn RDF graph built from a templateA graph of only the hostname triples of High assets
DESCRIBEAn RDF graph describing a resourceDESCRIBE 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.

  1. Parsing: checks the syntax of the query text and expands prefixes into full IRIs.
  2. 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.
  3. 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.
  4. Execution: how the query runs depends on where the data is stored.
  5. 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.
parsing syntax check algebra tree internal form optimization join order execution read data serialize JSON, XML SPARQL query result triple store match patterns with indexes virtualization SQL on the source DB
A query goes through parsing, the algebra tree, optimization, execution and serialization. How it executes depends on where the data is stored: index matching or SQL translation.
  • 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 assets and alerts with the condition criticality = '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