Derivation (electrostatic energy)
Discrete case
Assemble the configuration of $N$ charges one by one from infinity.
-
No work is done to bring $q_1$ from infinity to $\v x_1$: $W_1 = 0$.
-
For $q_2$, $$ \begin{align*} W_2 = \frac{q_1 q_2}{4πε_0|\v x_1 - \v x_2|}. \end{align*} $$
-
For $q_3$, $$ \begin{align*} W_3 = \frac{q_1 q_3}{4πε_0|\v x_1 - \v x_3|} + \frac{q_2 q_3}{4πε_0|\v x_2 - \v x_3|}, \end{align*} $$ etc.
So the total work done is $$ \begin{align*} U = \frac{1}{2} \sum_{i=1}^{N} \sum_{\substack{j=1\\j\neq i}}^{N} \frac{q_i q_j}{4πε_0 |\v x_j - \v x_i|}. \end{align*} $$
Continuous case
In terms of potentials
Either say the discrete case generalises, or:
Suppose we want to assemble the charge distribution $ρ(\v x)$, in which case the electrostatic potential is $Φ(\v x)$.
Consider a charge distribution $λ\, ρ(\v x)$. In this case by linearity of Maxwell's equations, the potential is $λ\, Φ(\v x)$. When we bring a small amount of charges in from infinity to make the charge distribution $(λ+δλ)ρ(\v x)$, the work done is $$ \begin{align*} δW = \int_{V} δλ\, ρ(\v x)\cdot λΦ(\v x) \d^3 \v x. \end{align*} $$ Thus integrating, $$ \begin{align*} W = \int_{0}^{1} \int_{V} ρ(\v x) \cdot λΦ(\v x) \d^3 \v x \d λ = \frac{1}{2}\int_{V} ρ(\v x)Φ(\v x) \d^3\v x. \end{align*} $$
In terms of electric fields
Use (M1) and $\v E = -∇Φ$, $$ \begin{align*} W ={}& \frac{ε_0}{2} \int_{V} (∇\cdot \v E)Φ \d^3 \v x \\ ={}& \frac{ε_0}{2} \int_{V} ∇\cdot (Φ\v E) - \v E\cdot ∇Φ \d^3 \v x \\ ={}& \frac{ε_0}{2} \left(\int_{\partial V} Φ\v E\cdot \d \v S + \int_{V} \v |\v E|^2 \d^3 \v x\right), \end{align*} $$ where we have applied the divergence theorem.
Now take $V$ to be a sphere of radius $R\to\infty$. Since $ρ$ is contained, by the multipole expansion, $Φ = O(R\inv)$ and $\v E = O(R^{-2})$ on $S$ while the area of $\partial V$ is $O(R^2)$. Thus the first term vanishes asymptotically and hence $$ \begin{align*} W = \int_{\R^3} \frac{1}{2}ε_0 |\v E|^2 \d^3 \v x. \end{align*} $$