VAR(expression) returns the sample variance of the non-null values, dividing by n - 1. In SQL that is var_samp(Sales). A group with a single value has no sample variance and returns null.
Updated · Checked on the xmetric engine
What is the syntax?
VAR(expression)
expression
a numeric field or row-level calculation.
Returns a real number: the sample variance, dividing by n - 1. Null when the group has no values or only one.
What does it return, and what is the SQL?
Each example runs on the same 12 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
What is the variance of sales in each region?
Tableau
VAR([Sales])
SQL (DuckDB)
SELECT Region, var_samp(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region
East's four sales values give 12,291.67. South has one value: null, since a sample needs two.
Region
Result
East
12,292
North
null
South
null
West
11,667
✓ The Tableau formula and the SQL return the same 4 rows.
Where does a straight translation go wrong?
Common mistake
Why does var_pop give a smaller variance?
VAR is the sample variance: it divides by n - 1. var_pop divides by n, the population version (VARP). East comes out at 12,291.67 against 9,218.75 for the population version.
Tableau
VAR([Sales])
Tempting SQL
SELECT Region, var_pop(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region
SQL that matches
SELECT Region, var_samp(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region
Region
Tableau
Tempting SQL
SQL that matches
East
12,292
9,219
12,292
North
null
null
null
South
null
0
null
West
11,667
8,750
11,667
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
What does VAR return for an all-null group and a single value?
North has two order lines and no sales value on either. Per product, Lamp has one line with a sale (row 4); the North lines have no product and no sales: null for both. Each result column is one mark, by Region.
Case
Tableau, then SQL (DuckDB)
East
North
South
West
all-null group
VAR([Sales])Region, var_samp(Sales)
12,292
null
null
11,667
one value
VAR([Sales])Product, var_samp(Sales)
133
9,250
null
null
✓ On every row, each Tableau formula and its SQL return the same value.
How do I write it in Snowflake or BigQuery?
The first example, written for each warehouse from its documentation. These are not run here; DuckDB is.
Snowflake
SELECT Region, VAR_SAMP(Sales) AS result
FROM input
GROUPBY Region
ORDERBY Region