Imagine you have two tables: Customers_US and Customers_EU. You want to get a list of all customers from both tables without duplicates. Why is combining result sets with UNION useful here?
Think about how to get a combined list without repeated entries.
UNION combines rows from multiple queries and removes duplicates, which is useful to get a unique list from different sources.
Given two tables:
Table A:
id | name
1 | Alice
2 | Bob
Table B:
id | name
2 | Bob
3 | Carol
What is the result of this query?
SELECT id, name FROM A
UNION
SELECT id, name FROM B;
Remember that UNION removes duplicates.
The UNION query returns all unique rows from both tables. Since '2 | Bob' appears in both, it shows only once.
You want to combine all rows from two tables including duplicates. Which query is correct?
Check the correct syntax for UNION ALL.
The correct syntax is UNION ALL with a space between UNION and ALL.
You have two large tables and want to combine their rows including duplicates. Why might UNION ALL be faster than UNION?
Think about what extra work UNION does compared to UNION ALL.
UNION removes duplicates which requires extra processing. UNION ALL just combines all rows directly, so it is faster.
Consider these two tables:
Employees: id INT, name VARCHAR(50)
Departments: dept_id INT, dept_name VARCHAR(50)
What error will this query cause?
SELECT id, name FROM Employees
UNION
SELECT dept_id FROM Departments;
Check how many columns each SELECT returns.
UNION requires each SELECT to return the same number of columns. Here, the first SELECT returns 2 columns, the second only 1.