The mean minimises the squared error
The mean is not only a convenient average. It is the one number closest to a list in the squared sense: no other value has a smaller total of squared distances to the data. That is why the variance is built from deviations about the mean, and why the mean appears in every least-squares calculation.
The same algebra has two consequences that are used without proof in the statistics chapters: the deviations from the mean add to zero, and a confidence interval and a two-sided test are the same calculation read two ways.
Before you start
Let the data be and let be any candidate for the centre. The total squared distance from is
The mean is . The claim is that is smallest when .
The proof
Differentiate with respect to :
Set the derivative to zero:
The second derivative is , which is positive, so this stationary point is a minimum. There is only one, because is a quadratic in .
Substituting into the derivative gives
so the deviations from the mean add to zero. That is the fact the standard deviation relies on: without it, the positive and negative deviations would cancel and the average deviation would always be zero.
The confidence interval and the test
A two-sided -test of rejects when
The right side is a fixed number for a given confidence level. Rearranging the inequality gives
Those are exactly the values outside the interval
So the test rejects precisely when the hypothesised mean lies outside the confidence interval. The two procedures are one calculation, not two that happen to agree. The same rearrangement works for the one-sample -test with in place of .
What this does not say
The mean minimises the squared error. A different loss gives a different centre: the median minimises the absolute error, and the mode minimises the error counted as a hit or a miss. Which centre is right depends on which loss matches the question.
The interval and the test agree only when both are two-sided and use the same standard error. A one-sided test corresponds to a one-sided interval, and a test with a different variance assumption corresponds to a different interval.