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 why we used the UNION ALL
statement and not the UNION
statement in the previous example. There is a subtle difference between them—the UNION
statement removes duplicated rows after merging results, so it is slower.
3.133.151.220