Introduction
UNION and UNION ALL combine results from two or more queries into one list. They help you see data from different places together.
SELECT column1, column2 FROM table1 UNION SELECT column1, column2 FROM table2;
SELECT name FROM customers_north UNION SELECT name FROM customers_south;
SELECT name FROM customers_north UNION ALL SELECT name FROM customers_south;
SELECT product FROM products_online UNION SELECT product FROM products_store;
CREATE TABLE fruits1 (name TEXT); CREATE TABLE fruits2 (name TEXT); INSERT INTO fruits1 VALUES ('Apple'), ('Banana'), ('Cherry'); INSERT INTO fruits2 VALUES ('Banana'), ('Date'), ('Apple'); -- Using UNION (removes duplicates) SELECT name FROM fruits1 UNION SELECT name FROM fruits2; -- Using UNION ALL (keeps duplicates) SELECT name FROM fruits1 UNION ALL SELECT name FROM fruits2;
UNION and UNION ALL in PostgreSQL?UNION combines results from two queries and removes duplicate rows to give unique results.UNION ALL combines results but keeps all rows, including duplicates.UNION removes duplicates, UNION ALL keeps duplicates. -> Option AUNION ALL in PostgreSQL?UNION ALL with a space between UNION and ALL.Table A:Table B:SELECT value FROM A UNION SELECT value FROM B ORDER BY value;
UNION removes duplicates, so 'banana' appears only once.SELECT id FROM table1 UNION ALL SELECT id FROM table2;
SELECT id, name FROM employees WHERE department = 'Sales'
SELECT id, name FROM contractors WHERE department = 'Sales'
UNION ALL because UNION removes duplicates.Pass the test and this pattern moves unknown