[SPARQL] Subquery

Subquery

How did I encounter this?

I got to use subquery to filter certain values but its syntax seems different from the one of MySQL. This post is about the difference.

Differences

A subquery in SPARQL is a nested SELECT statement placed inside another query’s { ... } block. While MySQL subqueries often appear in the WHERE or FROM clauses, SPARQL subqueries are typically placed inside braces to provide a temporary result set that the outer query can use.

MySQL

  • A subquery might appear after FROM ( SELECT ... ), in a WHERE clause, or even in SELECT. Subqueries are often used for conditions.
WHERE item IN (SELECT item FROM ...).

SPARQL

  • Subqueries are written as a complete SELECT inside curly braces. it's not possible to put them in every place like in SQL.
  • Subqueries are used to filter or collect certain bindings, then references them in the outer query.

Benefits of using subquery in SPARQL

  1. Performance

    • By narrowing down items in a subquery, you reduce the data the outer query must handle.
  2. Readability

    • Splits complex filtering (subquery) from data gathering or aggregation (outer query).
  3. Avoid Timeouts

    • SPARQL endpoints like Wikidata often time out for complex, single-query logic. Subqueries can help break it into two simpler steps.

Example of a SPARQL Subquery

SELECT ?item ?itemLabel
WHERE {
  # Step 1: Subquery to find items (nested)
  {
    SELECT DISTINCT ?item
    WHERE {
      ?item wdt:P31 wd:Q7889.       # item is an instance of a video game
      ?item rdfs:label ?lbl.
      FILTER(CONTAINS(LCASE(?lbl), "final fantasy 16"))
    }
  }

  # Step 2: Use the filtered items to get more data
  ?item rdfs:label ?itemLabel.
  FILTER(LANG(?itemLabel) = "en").
 
  OPTIONAL {
    ?item skos:altLabel ?alias.
    FILTER(LANG(?alias) = "en")
  }
}

Comments