Introduction
Use INTERSECT and EXCEPT to find common or different data between two lists or tables easily.
SELECT column_list FROM table1 INTERSECT SELECT column_list FROM table2; SELECT column_list FROM table1 EXCEPT SELECT column_list FROM table2;
SELECT name FROM employees_2023 INTERSECT SELECT name FROM employees_2024;
SELECT product_id FROM sales_january EXCEPT SELECT product_id FROM sales_february;
SELECT city FROM customers_us INTERSECT SELECT city FROM customers_canada;
CREATE TABLE fruits1 (name TEXT); CREATE TABLE fruits2 (name TEXT); INSERT INTO fruits1 VALUES ('apple'), ('banana'), ('cherry'); INSERT INTO fruits2 VALUES ('banana'), ('cherry'), ('date'); -- Find fruits in both lists SELECT name FROM fruits1 INTERSECT SELECT name FROM fruits2; -- Find fruits in fruits1 but not in fruits2 SELECT name FROM fruits1 EXCEPT SELECT name FROM fruits2;
INTERSECT operator do in PostgreSQL?table1 but not in table2 using EXCEPT?table_a:table_b:SELECT id FROM table_a INTERSECT SELECT id FROM table_b;SELECT id, name FROM table1 EXCEPT SELECT id FROM table2;
employees with columns id, namecontractors with columns id, namePass the test and this pattern moves unknown