3.3.19. UNION

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

3.3.19.1. Introduction

UNION 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 3.18. Graph
alt

3.3.19.2. Combine two queries and retain duplicates

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.

Table 3.106. Result
name

4 rows

"Anthony Hopkins"

"Helen Mirren"

"Hitchcock"

"Hitchcock"

Try this query live.  CREATE (ah:Actor {name: 'Anthony Hopkins'}), (hm:Actor {name: 'Helen Mirren'}), (hitchcock:Actor {name: 'Hitchcock'}), (hitchcockMovie:Movie {title: 'Hitchcock'}), (ah)-[:KNOWS]->(hm), (ah)-[:ACTS_IN]->(hitchcockMovie), (hm)-[:ACTS_IN]->(hitchcockMovie) MATCH (n:Actor) RETURN n.name AS name UNION ALL MATCH (n:Movie) RETURN n.title AS name

3.3.19.3. 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.

Table 3.107. Result
name

3 rows

"Anthony Hopkins"

"Helen Mirren"

"Hitchcock"

Try this query live.  CREATE (ah:Actor {name: 'Anthony Hopkins'}), (hm:Actor {name: 'Helen Mirren'}), (hitchcock:Actor {name: 'Hitchcock'}), (hitchcockMovie:Movie {title: 'Hitchcock'}), (ah)-[:KNOWS]->(hm), (ah)-[:ACTS_IN]->(hitchcockMovie), (hm)-[:ACTS_IN]->(hitchcockMovie) MATCH (n:Actor) RETURN n.name AS name UNION MATCH (n:Movie) RETURN n.title AS name