SPARQL, RDF Datasets, FROM, FROM NAMED, and GRAPH
Bob DuCharme suggested that I share this explanation about the role of FROM, FROM NAMED, and GRAPH within a SPARQL query. So here it is…
A SPARQL query goes against an RDF dataset. An RDF dataset has two parts:
- A single default graph -- a set of triples with no name attached to them
- Zero or more named graphs -- each named graph is a pair of a name and a set of triples
The FROM and FROM NAMED clauses are used to specify the RDF dataset.
The statement "FROM u" instructs the SPARQL processor to take the graph that it knows as "u", take all the triples from it, and add them to the single default graph. If you then also have "FROM v", then you take the triples from the graph known as v and also add them to the default graph.
The statement "FROM NAMED x" instructs the SPARQL processor to take the graph that it knows as "x", take all the triples from it, pair it up with the name "x", and add that pair (x, triples from x) as a named graph in the RDF dataset.
Note that "known as" is purposefully not specified -- some implementations dereference the URI to get the triples that make up that graph; others just use a graph store that maps names to triples.
All the parts of the query that are outside a GRAPH clause are matched against the single default graph.
All the parts of the query that are inside a GRAPH clause are matched individually against the named graphs.
This is why it sometimes makes sense to specify the same graph for both FROM and FROM NAMED:
FROM NAMED x
...puts the triples from x in the default graph and also includes x as a named graph. So that later in the query, triple patterns outside of a GRAPH clause can match parts of x and so can triple patterns inside a GRAPH clause.
There's a visual picture of this on slide 13 of my SPARQL Cheat Sheet slides.