This returns a combined list of unique cities from both tables.
SELECT city FROM customers
UNION
SELECT city FROM suppliers;When using UNION or UNION ALL to combine the results of two or more SELECT statements, it's important that the queries involved meet specific compatibility requirements:
SELECT statements must return the same number of columns.SELECT must be of compatible or convertible data types (e.g., string with string, number with number).SELECT statement.-- Both queries must return 2 columns: a name and a country
SELECT name, country FROM customers
UNION
SELECT supplier_name, country FROM suppliers;In this example:
name from customers and supplier_name from suppliers are expected to be text-compatible.country is used in both queries and should be of the same type (e.g., VARCHAR).If the structure or types don't match, the SQL engine will raise an error. Always test your queries independently first, and ensure alignment before using UNION.
This includes all duplicates. Faster than UNION because it skips deduplication.
SELECT country FROM customers
UNION ALL
SELECT country FROM suppliers;Apply ORDER BY after the final SELECT statement, not within each SELECT.
SELECT name FROM employees
UNION
SELECT name FROM managers
ORDER BY name;Ask the AI if you need help understanding or want to dive deeper in any topic