Junior
What is the UNION operator in SQL and what data does it compare?
sobes.tech AI
Answer from AI
The UNION operator combines the results of two or more SELECT statements.
It compares and merges rows from the result sets. To successfully use UNION:
- The number of columns in each
SELECTstatement must be the same. - The data types of the corresponding columns in each
SELECTstatement should be compatible (though not necessarily identical). For example, you can combineINTandFLOAT, but notINTandBLOB.
UNION by default removes duplicate rows from the combined result. To include duplicates, use UNION ALL.
Example:
-- Get all customer and supplier names, excluding duplicates
SELECT Name FROM Customers
UNION
SELECT Name FROM Suppliers;
Example with UNION ALL:
-- Get all customer and supplier names, including duplicates
SELECT Name FROM Customers
UNION ALL
SELECT Name FROM Suppliers;