COVAR(expression1, expression2) measures how two numbers move together across the rows of a group, dividing by n - 1, where n counts the rows where both values are present. In SQL it is covar_samp(Sales, Units). Rows with a null on either side are left out.
Updated · Checked on the xmetric engine
What is the syntax?
COVAR(expression1, expression2)
expression1, expression2
two numeric fields or row-level calculations, paired row by row.
Returns a real number: the sample covariance over rows where both values are non-null. Null when there are none or only one pair.
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.
How do sales and units move together in each region?
Tableau
COVAR([Sales], [Units])
SQL (DuckDB)
SELECT Region, covar_samp(Sales, Units) AS result
FROM input
GROUPBY Region
ORDERBY Region
East pairs four lines (row 2 has no sales); West pairs three (row 7 has no units). South has one pair: null.
Region
Result
East
192
North
null
South
null
West
200
✓ The Tableau formula and the SQL return the same 4 rows.
Where does a straight translation go wrong?
Common mistake
Why does covar_pop give a different covariance?
COVAR is the sample covariance and divides by n - 1. covar_pop divides by n, which is Tableau's COVARP.
Tableau
COVAR([Sales], [Units])
Tempting SQL
SELECT Region, covar_pop(Sales, Units) AS result
FROM input
GROUPBY Region
ORDERBY Region
SQL that matches
SELECT Region, covar_samp(Sales, Units) AS result
FROM input
GROUPBY Region
ORDERBY Region
Region
Tableau
Tempting SQL
SQL that matches
East
192
144
192
North
null
null
null
South
null
0
null
West
200
133
200
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
Common mistake
Why does filling nulls with 0 change the covariance?
Tableau drops a row when either value is null. coalesce(Sales, 0) keeps row 2 as a sale of 0 with 3 units, which pulls East's covariance down.
Tableau
COVAR([Sales], [Units])
Tempting SQL
SELECT Region,
covar_samp(coalesce(Sales, 0), coalesce(Units, 0)) AS result
FROM input
GROUPBY Region
ORDERBY Region
SQL that matches
SELECT Region, covar_samp(Sales, Units) AS result
FROM input
GROUPBY Region
ORDERBY Region
Region
Tableau
Tempting SQL
SQL that matches
East
192
130
192
North
null
0
null
South
null
null
null
West
200
133
200
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
What does COVAR return for an all-null group and a single pair?
North has two order lines and no sales value on either. Per product, Lamp has one complete pair (row 4) and the unnamed North lines none: null for both. Each result column is one mark, by Region.