The UNION statement
Suppose we want to know how many books and how many authors are stored in our database. We can perform two queries to get these values, but with the UNION
statement, we can merge these data together. Just put the UNION
keyword between two or more queries, as shown in the following query:
MATCH (b:Book)
RETURN 'Books' as type, COUNT(b) as cnt
UNION ALL
MATCH (a:Person)
RETURN 'Authors' as type, COUNT(a) as cnt
The result is as follows:
+-----------------+ | type | cnt | +-----------------+ | "Books" | 150 | | "Authors" | 142 | +-----------------+
The only condition we must be careful of with the UNION
statement is that the result set must have the same number of columns and the columns must have the same names.
You're perhaps wondering ...
Get Learning Cypher now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.