Set difference

3 snippets across 3 stacks — JavaScript, Python, SQL

Also written as Set difference

JSJavaScript

Set Methods (ES2025)

JS · Modern Features
syntax
setA.union(setB)
setA.intersection(setB)
setA.difference(setB)
setA.symmetricDifference(setB)
setA.isSubsetOf(setB)
setA.isSupersetOf(setB)
setA.isDisjointFrom(setB)
example
const frontend = new Set(["js", "css", "html", "ts"]);
const backend = new Set(["js", "python", "go", "ts"]);

console.log(frontend.union(backend));
// Set {"js", "css", "html", "ts", "python", "go"}

console.log(frontend.intersection(backend));
// Set {"js", "ts"}

console.log(frontend.difference(backend));
// Set {"css", "html"}

console.log(frontend.isSubsetOf(backend)); // false

Note ES2025. All methods return new Sets (non-mutating). Works with any iterable argument, not just Sets. Replaces manual loop-based set operations.

PYPython

Set Operations

PY · Tuples & Sets
syntax
a | b  (union)
a & b  (intersection)
a - b  (difference)
a ^ b  (symmetric difference)
example
frontend = {"alice", "bob", "carol"}
backend = {"bob", "carol", "dave"}

print(frontend | backend)
print(frontend & backend)
print(frontend - backend)
print(frontend ^ backend)
output
{'alice', 'bob', 'carol', 'dave'}
{'bob', 'carol'}
{'alice'}
{'alice', 'dave'}

Note Set operations are extremely fast (O(min(len(a), len(b))) for intersection). Use them instead of nested loops for membership checks.

SQLSQL

INTERSECT and EXCEPT

SQL · Advanced
syntax
SELECT columns FROM table1
INTERSECT
SELECT columns FROM table2;

SELECT columns FROM table1
EXCEPT
SELECT columns FROM table2;
example
-- Customers who are also employees
SELECT email FROM customers
INTERSECT
SELECT email FROM employees;

-- Customers who are NOT employees
SELECT email FROM customers
EXCEPT
SELECT email FROM employees;
output
-- INTERSECT: emails in both tables
-- EXCEPT: emails only in customers

Note INTERSECT returns rows in both result sets. EXCEPT returns rows in the first set but not the second. MySQL 8.0.31+ supports these; earlier versions do not. SQL Server calls EXCEPT what PostgreSQL calls EXCEPT — they are the same. MINUS is Oracle's synonym for EXCEPT.