SQL
Combine Result Sets from Multiple Queries with UNION ALL
Efficiently merge the results of two or more SELECT statements into a single result set using the UNION ALL operator, useful for combining similar data from different tables.
SELECT
customer_id, customer_name, 'active' AS status
FROM
active_customers
WHERE
last_activity_date >= DATE('now', '-90 days')
UNION ALL
SELECT
customer_id, customer_name, 'inactive' AS status
FROM
inactive_customers
WHERE
last_activity_date < DATE('now', '-90 days')
UNION ALL
SELECT
customer_id, customer_name, 'new' AS status
FROM
new_signups
WHERE
signup_date >= DATE('now', '-30 days');
How it works: This SQL query uses `UNION ALL` to combine results from multiple `SELECT` statements into a single dataset. It's useful for merging similar data (e.g., customer information) from different tables or based on different criteria, like active, inactive, or new customers. `UNION ALL` includes all rows, including duplicates, making it generally faster than `UNION` which filters out duplicates. Each `SELECT` statement must have the same number of columns with compatible data types and in the same order.