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

Tip

If you don't care about duplicated rows, or you already know that your result set has no duplicates, use the UNION ALL statement because it faster than the UNION statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.151.220