10.7. Union

The UNION clause is used to combine the result of multiple queries.

It combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union.

The number and the names of the columns must be identical in all queries combined by using UNION.

To keep all the result rows, use UNION ALL. Using just UNION will combine and remove duplicates from the result set.

Figure 10.6. Graph

Combine two queries

Combining the results from two queries is done using UNION ALL.

Query 

MATCH (n:Actor)
RETURN n.name AS name
UNION ALL MATCH (n:Movie)
RETURN n.title AS name

The combined result is returned, including duplicates.

Result

name
4 rows

"Anthony Hopkins"

"Helen Mirren"

"Hitchcock"

"Hitchcock"

Try this query live create (_0:`Actor` {`name`:"Anthony Hopkins"}) create (_1:`Actor` {`name`:"Helen Mirren"}) create (_2:`Actor` {`name`:"Hitchcock"}) create (_3:`Movie` {`title`:"Hitchcock"}) create (_0)-[:`ACTS_IN`]->(_3) create (_0)-[:`KNOWS`]->(_1) create (_1)-[:`ACTS_IN`]->(_3) ; match (n:Actor) return n.name as name UNION ALL match (n:Movie) return n.title as name

Combine two queries and remove duplicates

By not including ALL in the UNION, duplicates are removed from the combined result set

Query 

MATCH (n:Actor)
RETURN n.name AS name
UNION
MATCH (n:Movie)
RETURN n.title AS name

The combined result is returned, without duplicates.

Result

name
3 rows

"Anthony Hopkins"

"Helen Mirren"

"Hitchcock"

Try this query live create (_0:`Actor` {`name`:"Anthony Hopkins"}) create (_1:`Actor` {`name`:"Helen Mirren"}) create (_2:`Actor` {`name`:"Hitchcock"}) create (_3:`Movie` {`title`:"Hitchcock"}) create (_0)-[:`ACTS_IN`]->(_3) create (_0)-[:`KNOWS`]->(_1) create (_1)-[:`ACTS_IN`]->(_3) ; match (n:Actor) return n.name as name UNION match (n:Movie) return n.title as name