Union of two selects in a SPARQL query

24,168

Solution 1

Based on @user205512's answer, here's one that works on Virtuoso:

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

The trick was just do add an additional ?s foaf:page ?page triple outside of the UNION. This is obviously redundant, but it seems to avoid the Virtuoso bug, which is apparently caused when you have a “naked” UNION with subqueries.

Solution 2

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) }
}
Share:
24,168
Timm
Author by

Timm

Website Developer

Updated on May 30, 2020

Comments

  • Timm
    Timm about 4 years

    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?