STDDEV Pop Versus SAMP Denominators

var_pop divides by n while var_samp divides by n-1, so one-row samples return NULL under samp but 0 under pop, and the same split applies to stddev.

SqlData Integrity

Code

snippet
-- the denominators differ: pop divides by n, samp divides by n-1
-- stddev 是 var 的平方根,遵循同一分母规律
CREATE TEMP TABLE probe_runs (
    run_id  int PRIMARY KEY,
    seconds numeric NOT NULL
);

INSERT INTO probe_runs VALUES
    (1, 2.0), (2, 4.0), (3, 4.0), (4, 10.0);

-- 四个观测值:样本方差(n-1 分母)恒大于等于总体方差(n 分母)
SELECT
    count(*)             AS n,
    var_pop(seconds)     AS var_pop,
    var_samp(seconds)    AS var_samp,
    stddev_pop(seconds)  AS stddev_pop,
    stddev_samp(seconds) AS stddev_samp
FROM probe_runs;

-- 单行样本:var_samp 分母 n-1=0 直接 NULL,var_pop 仍然是 0
SELECT
    var_pop(seconds)     AS var_pop_one_row,
    var_samp(seconds)    AS var_samp_one_row,
    stddev_pop(seconds)  AS stddev_pop_one_row,
    stddev_samp(seconds) AS stddev_samp_one_row
FROM probe_runs
WHERE run_id = 1;

-- 当窗口函数用:逐行标注全体口径的方差,行数不塌缩
SELECT
    run_id,
    seconds,
    stddev_pop(seconds)  OVER () AS pop_all,
    stddev_samp(seconds) OVER () AS samp_all
FROM probe_runs
ORDER BY run_id;

The denominator is the whole difference

var_pop divides the squared deviations by n; var_samp divides by n−1 (Bessel’s correction), so on the same data the sample variance is always greater than or equal to the population one. For the four runs (2.0, 4.0, 4.0, 10.0, mean 5), the squared deviations sum to 36: var_pop returns 9 and var_samp returns 12; stddev_pop is their square root 3 and stddev_samp is √12 ≈ 3.46. The single-row query is where the split becomes visible as types: with n = 1 the samp denominator is zero, so var_samp and stddev_samp return NULL, while the pop flavor returns a well-defined 0.

The three result sets

 n | var_pop | var_samp | stddev_pop | stddev_samp
---+---------+----------+------------+-------------
 4 |       9 |       12 |          3 | 3.4641…

 var_pop_one_row | var_samp_one_row | stddev_pop_one_row | stddev_samp_one_row
-----------------+------------------+--------------------+---------------------
               0 |                  |                  0 |

The third query re-runs both aggregates as window functions with OVER () — the whole partition as one frame — so each of the four rows is annotated with 3 and the sample value while the row count never collapses.

The line that annotates per row

stddev_pop(seconds)  OVER () AS pop_all,

OVER () with no partition or order treats every row as one group — the aggregate value repeats on each row instead of shrinking the result to one row.

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`probe_runs`.