Statistical aggregates
Overview
Variance describes spread around a mean; standard deviation is its square root, in the original measurement units. Population variance divides squared deviations by N; sample variance uses N−1 to estimate population variance from a sample. Choose based on what the data represents.
First example
SELECT COUNT(score), AVG(score) FROM sort_scores;Observed SQLite result (rows in JSON):
[ [ 2, 5 ]]How it works
For the two known scores 0 and 10, mean = 5, squared deviations total 50, population variance = 25 and sample variance = 50. The small SQLite calculation below uses the known mean 5 explicitly to illustrate the formula; it is not a general variance implementation. PostgreSQL 17 has VAR_POP, VAR_SAMP, STDDEV_POP, STDDEV_SAMP, covariance and correlation functions. Pairwise statistics exclude rows with either input missing. The local SQLite build lacks native VAR_POP and STDDEV_POP.
Practical example
SELECT AVG((score - 5.0)*(score - 5.0)) AS pop_variance, SUM((score - 5.0)*(score - 5.0)) / NULLIF(COUNT(score)-1,0) AS sample_variance FROM sort_scores;Observed SQLite result (rows in JSON):
[ [ 25, 50 ]]Practice and mistakes
Never use a sample variance with fewer than two observations; PostgreSQL returns NULL in that case. Do not equate correlation with causation. Practice: explain why standard deviation of these two population values is 5, while variance is 25 in squared units. For real datasets prefer a tested native aggregate or numerically stable implementation.
PostgreSQL 17 — not executed
SELECT VAR_POP(score), VAR_SAMP(score), STDDEV_POP(score) FROM sort_scores;Expected result: 25, 50, 5