Combine results from multiple subqueries using the UNION statement
What is a UNION statement?
The UNION statement is used to combine results of two or more subqueries. It can be used in combination with another SQL commands.
SELECT * FROM customers
SELECT * FROM employees
This code selects all results from the collection customers and concatenates it with all results from the collection employees. If some fields are not present in one of the collections, the are filled with NULLs.
Using UNION with WHERE
In the following example, we union two subqueries on the same collection with different WHERE condition.
SELECT id, price FROM products
WHERE NOT taxable
SELECT id, price * 1.15 AS price FROM products
UNION WHERE can be used to build complex logic into your reports, however, in the previous example, it would be more efficient to use simple IF function.
SELECT id, IF (taxable, price * 1.15, price) as price FROM products
You are now armed with useful knowledge of combining data with the UNION statement. Here are more articles to help you with your data analytics tasks with Jetspike.