Working with UNION in Cypher
The UNION
clause combines the results of two or more queries and returns the results. It works pretty similarly to how it works in SQL queries. Normally, we use the UNION
clause when we want to combine the results of multiple, disparate queries returning similar datasets.
Let’s look at an example usage of the UNION
clause:
MATCH (p:Patient)-[:HAS_ENCOUNTER]->()-[:HAS_DIAGNOSIS]->(d) WHERE p.id='f237e253-9052-a038-7c9e-dbd9a1d7da32' RETURN d.code as drug UNION MATCH (p:Patient)-[:HAS_ENCOUNTER]->()-[:HAS_DIAGNOSIS]->(d) WHERE p.id='ffa580de-08e5-9a47-b12a-db312ad6825b' RETURN d.code as drug
This query returns the diagnosis codes used among two patients, as shown in the following figure:
Figure 6.13 – Usage of the UNION clause
We can see there are five records returned. The UNION
clause eliminates duplicate records in the results if there are any.
We could have written the...