Union of two selects in a SPARQL query

Timm picture Timm · May 29, 2012 · Viewed 21.2k times · Source

I'd like to do something like

{
    SELECT ?page, "A" AS ?type WHERE 
    {
         ?s rdfs:label "Microsoft"@en;
            foaf:page ?page
    }
}
UNION
{
    SELECT ?page, "B" AS ?type WHERE 
    {
         ?s rdfs:label "Apple"@en;
            foaf:page ?page
    }
}

But this gives a syntax error. How can I union two select queries in SPARQL?

Answer

user205512 picture user205512 · May 29, 2012

You can union them like this:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT * WHERE
{ 
{
    SELECT ?page ("A" AS ?type) WHERE 
    {
         ?s rdfs:label "Microsoft"@en;
            foaf:page ?page
    }
}
UNION
{
    SELECT ?page ("B" AS ?type) WHERE 
    {
         ?s rdfs:label "Apple"@en;
            foaf:page ?page
    }
}
}

(check with the SPARQL validator)

However I don't think you need sub queries at all for this case. For example:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT ?page ?type WHERE
{
    ?s foaf:page ?page .
    { ?s rdfs:label "Microsoft"@en . BIND ("A" as ?type) }
    UNION
    { ?s rdfs:label "Apple"@en . BIND ("B" as ?type) }
}