Middle
What are the main limitations when performing a Union operation in SQL?
sobes.tech AI
Answer from AI
Main restrictions when performing the UNION operation in SQL:
- Number of columns: The SELECT queries must contain the same number of columns.
- Order of columns: Corresponding columns in both queries must have compatible (or identical) data types. The order of columns must also be the same.
- Column names: The result of
UNIONinherits column names from the first SELECT query. UNION ALLversusUNION:UNIONby default removes duplicate rows, which can be resource-intensive for large datasets.UNION ALLincludes all rows, including duplicates, and is usually more performant.
Example:
SELECT id, name, city
FROM employees
UNION
SELECT id, name, '' AS city -- Added an empty string column to match the number of columns
FROM contractors
WHERE type = 'external'; -- Example condition that may lead to different data types without explicit casting