How to write a UNION in SPARQL.

In DBPedia, I want to get a list of presidents born in 1945.
A president is either a "onto:President" or a "yago:President".
So a UNION is needed to manage both.

One way to write the corresponding SPARQL query is :

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX onto: <http://dbpedia.org/ontology/>
PREFIX yago: <http://dbpedia.org/class/yago/>
SELECT DISTINCT ?uri ?string
WHERE
{
	{
		?uri rdf:type onto:President .
		?uri onto:birthDate ?date .
		FILTER regex(?date, "^1945") .
                OPTIONAL {?uri rdfs:label ?string .}
                FILTER (lang(?string) = "en")
	}
	UNION
	{
		?uri rdf:type yago:President.
		?uri onto:birthDate ?date .
		FILTER regex(?date, "^1945") .
                OPTIONAL {?uri rdfs:label ?string .}
                FILTER (lang(?string) = "en")
	}
}

Another way is :

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX onto: <http://dbpedia.org/ontology/>
PREFIX yago: <http://dbpedia.org/class/yago/>
SELECT DISTINCT ?uri ?string
WHERE
{
	{{
		?uri rdf:type onto:President .
		
	}
	UNION
	{
		?uri rdf:type yago:President.

	}}.
?uri onto:birthDate ?date .
		FILTER regex(?date, "^1945") .
                OPTIONAL {?uri rdfs:label ?string .}
                FILTER (lang(?string) = "en")
}

Received on Wednesday, 16 February 2011 09:49:39 UTC