PostgreSQL variance() Function

The PostgreSQL variance() function is an aggregate function that computes the sample variance (square of the sample standard deviation) for all non-null input values. It is var_samp() an alias for .

variance() Syntax

Here is the syntax of the PostgreSQL variance() function:

variance(expr)

Typically, we use the variance() function like:

SELECT variance(expr), ...
FROM table_name
[WHERE ...]
[GROUP BY group_expr1, group_expr2, ...];

Parameters

expr

Required. A column name or expression.

Return value

The PostgreSQL variance() function returns the sample variance (square of the sample standard deviation) for all non-null input values.

Note that the variance() function only handles non-null values. That is, null values ​​are ignored by the variance() function.

variance() Examples

To demonstrate usages of the PostgreSQL variance() function, we simulate a temporary table using the following statement with UNION and SELECT:

SELECT 4 x
UNION
SELECT 5 x
UNION
SELECT 6 x;
 x
---
 4
 6
 5
(3 rows)

The following statement uses the variance() function to calculate the sample variance of all the values ​​in the x column:

SELECT variance(x)
FROM (
    SELECT 4 x
    UNION
    SELECT 5 x
    UNION
    SELECT 6 x
  ) t;
        variance
------------------------
 0.66666666666666666667
(1 rows)