In MySQL, the output of two or more SELECT statements is combined using a UNION. It can be utilized when it is required to fetch data from many tables or views having similar structures.
For instance, you could use a UNION to retrieve all of a customer’s orders, whether they were placed in person or online.
SELECT order_id, order_date, ‘online’ as source FROM online_orders WHERE customer_id = 789 UNION
SELECT order_id, order_date, ‘in-person’ as source FROM in_person_orders WHERE customer_id = 789;
Here, UNION combines the result of two SELECT
statements, one for online orders and one for in-person orders, and adds a new column to check the source of each order. Regardless of where the orders were placed, the subsequent query would return all of customer 789’s orders.