Question

In this simple sparql query I get a list of subjects whose object is 42

SELECT ?v WHERE { ?v ?p 42 }

If I add ?p as a variable

SELECT ?v ?p WHERE { ?v ?p 42 }

I will get two entities per row, the subject and the predicate. What if I wanted three entities, so including the 42? Something like:

SELECT ?v ?p ?m WHERE { ?v ?p (42 as m) }
Was it helpful?

Solution

Standard SPARQL 1.0 does not really allow that. There may be some implementation-specific extensions for doing it, though.

As a workaround, if the data contains a triple with 42 as an object literal, you can do it e.g. like this:

SELECT ?v ?p ?m { ?v ?p 42, ?m FILTER(?m=42)}

which is equivalent with

 SELECT ?v ?p ?m WHERE { ?v ?p 42 . ?v ?p ?m FILTER(?m=42)}

as you can write graph patterns sharing the same subject and predicate with the comma object list notation, and the WHERE keyword is optional.

For efficiency, you want to use basic graph patterns to reduce the working triple to a smaller set and only then apply FILTER expressions to further prune the results.

OTHER TIPS

Another variant is to use BIND, e.g.:

SELECT ?v ?p ?m
WHERE {
  BIND(42 AS ?m)
  ?v ?p ?m
}

The BIND statement simply adds a binding for ?m, which can then be selected for the result set.

In SPARQL 1.1, you can use VALUES for this. You would write

SELECT ?v ?p ?m WHERE {
  values ?m { 42 }
  ?v ?p ?m
}

You can accomplish in two ways using BINDINGS keyword as well as FILTER

Using BINDINGS

SELECT ?v ?p ?m 
WHERE { ?v ?p ?m}
BINDINGS ?m {(42)}

Using FILTER

SELECT ?v ?p ?m
WHERE {
?v ?p ?m
FILTER (?m = 42)
}
select ?v ?p ?m where { ?v ?p ?m . FILTER( ?m = 42 ) }

I know this is round-about, but I believe this is doable with a subquery.

This is a useful pattern to help you work on the query in the narrow, before you let it loose on your entire dataset:

SELECT ?v ?p ?m WHERE {
   { SELECT 42 as ?m WHERE { } }
   ?v ?p ?m .
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top