Set difference (source code)

= Set difference
{title2=$A\setminus B$}

= Relative complement
{synonym}

The set difference $A\setminus B$ keeps the <set elements> of $A$ that do not belong to $B$:
$$
A\setminus B=\{x\in A:x\notin B\},\qquad x\in A\setminus B\iff(x\in A)\wedge\neg(x\in B).
$$
Thus <set difference> combines <logical conjunction> (AND) with <logical negation> (NOT): pass the first condition and fail the second. The definition applies to any two <sets>; $B$ need not be a <subset> of $A$.

For $A=\{1,2,3\}$ and $B=\{3,4\}$, the two orders give different answers:
$$
A\setminus B=\{1,2\},\qquad B\setminus A=\{4\}.
$$
The common member $3$ is removed in both directions. A database filter illustrates the usefulness: if $A$ is the <set> of records matching the first condition and $B$ the <set> matching the second, $A\setminus B$ selects records matching the first but not the second. The <Venn diagram> in <set union> shades both directions separately.

The name <relative complement> emphasizes that the ambient <set> is $A$: $A\setminus B$ is the <complement> of $A\cap B$ within $A$. If a larger <universal set> $U$ contains $A$ and $B$, then $A\setminus B=A\cap(U\setminus B)$. Changing that larger <universal set> does not change the <set difference>, because membership still requires belonging to $A$. In <ZF> the <set difference> exists by the <axiom schema of separation>. It also gives <relative complements> within a fixed <tuple> <domain> in <finite relation closure for set-theoretic coding>.