Combines results from multiple queries.
<query1>
UNION [ALL]
<query2>
## Overview UNION combines the result sets of two or more Cypher queries into a single result set. By default, UNION deduplicates rows; UNION ALL retains all rows including duplicates. Each constituent query must produce the same number of columns with compatible types. In DeltaForge, UNION operates on the Arrow RecordBatch output of each sub-query. The column names of the final result are determined by the first query in the UNION chain. Subsequent queries must return the same number of columns, and the column types must be compatible for vertical concatenation. ## Behavior - UNION (without ALL) performs deduplication by comparing all column values row by row. This requires materializing both result sets and performing a distinct operation. - UNION ALL concatenates results without deduplication, which is faster and uses less memory. - Column names in the final output come from the first query's RETURN aliases. Aliases in subsequent queries are ignored for naming but must still be type-compatible. - Multiple UNION or UNION ALL clauses can be chained to combine three or more queries. - Each sub-query in a UNION is executed independently. They can reference different parts of the graph or use different MATCH patterns. ## Limitations - All constituent queries must return the same number of columns. A mismatch produces a parse error. - Column types must be compatible across queries. Combining an integer column with a string column may produce type coercion errors. - Mixing UNION and UNION ALL in the same chain is not supported. Use a consistent approach (either all UNION or all UNION ALL).
| Name | Type | Description |
|---|---|---|
all | Enables retention of duplicate rows in the combined result. When false (the default), UNION deduplicates the combined rows. When true (UNION ALL), all rows from both queries are included. |
-- Combine results from two label-filtered queries
USE my_zone.my_schema.my_graph
MATCH (n:Employee)
WHERE n.department = 'Engineering'
RETURN n.name AS name, n.department AS dept
UNION
MATCH (n:Employee)
WHERE n.department = 'Marketing'
RETURN n.name AS name, n.department AS dept;
-- UNION ALL to preserve duplicates
USE my_zone.my_schema.my_graph
MATCH (a)-[:mentor]->(b)
RETURN a.name AS person, 'mentor' AS role
UNION ALL
MATCH (a)-[:colleague]->(b)
RETURN a.name AS person, 'colleague' AS role;
-- Combine node and edge counts
USE my_zone.my_schema.my_graph
MATCH (n)
RETURN 'nodes' AS entity, count(n) AS total
UNION ALL
MATCH ()-[r]->()
RETURN 'edges' AS entity, count(r) AS total;
-- Multi-way UNION for three relationship types
USE my_zone.my_schema.my_graph
MATCH (a)-[:mentor]->(b)
RETURN a.name AS source, b.name AS target, 'mentor' AS type
UNION ALL
MATCH (a)-[:colleague]->(b)
RETURN a.name AS source, b.name AS target, 'colleague' AS type
UNION ALL
MATCH (a)-[:teammate]->(b)
RETURN a.name AS source, b.name AS target, 'teammate' AS type;