W3. SQL Union Flashcards
Q: What does the SQL UNION operator do?
A: It combines the result sets of two or more SELECT statements into a single result set.
Q: What requirements must be met for UNION to work?
A: Each SELECT statement must have the same number of columns, with similar data types, and the columns must be in the same order.
Q: Write the syntax for a basic UNION.
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Q: What does UNION ALL do differently than UNION?
A: UNION ALL includes duplicate values, whereas UNION only returns distinct values.
Q: Write the syntax for UNION ALL.
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Q: Write a query to return distinct cities from both “Customers” and “Suppliers”.
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Q: How can you modify a UNION to include duplicate values?
A: Use UNION ALL instead of UNION.
Q: Write a query to return German cities (distinct) from both “Customers” and “Suppliers”.
SELECT City, Country FROM Customers
WHERE Country = ‘Germany’
UNION
SELECT City, Country FROM Suppliers
WHERE Country = ‘Germany’
ORDER BY City;
Q: Write a query to list all customers and suppliers, labeling each as “Customer” or “Supplier”.
SELECT ‘Customer’ AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT ‘Supplier’, ContactName, City, Country
FROM Suppliers;
Q: What is the purpose of using AS Type in the last example?
A: It creates an alias, Type, to indicate whether each record is a “Customer” or a “Supplier”.