ZN(expression) returns the expression, or 0 when it is null. In SQL that is coalesce(x, 0) (Snowflake also has ZEROIFNULL, BigQuery IFNULL(x, 0)). Where it goes matters: ZN([a]) + ZN([b]) replaces each null before adding, while coalesce(a + b, 0) throws away the value that was there.
Updated · Checked on the xmetric engine
What is the syntax?
ZN(expression)
expression
a number or a numeric expression, row-level or aggregate.
Returns the expression, or 0 if it is null. Same type as the expression.
What does it return, and what is the SQL?
Each example runs on the same 8 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
What is each value, with nulls as zero?
Tableau
ZN([Value])
SQL (DuckDB)
SELECTcoalesce(Value, 0) AS result
FROM input
ORDERBY id
Row 6 has no value, so it becomes 0.
Value
Result
2.5
2.5
−2.5
−2.5
0.13
0.13
−0.4
−0.4
3.75
3.75
0
0
0
16
16
✓ The Tableau formula and the SQL return the same 8 rows.
What do two fields add up to when either can be null?
Tableau
ZN([Value]) +ZN([Other])
SQL (DuckDB)
SELECTcoalesce(Value, 0) +coalesce(Other, 0) AS result
FROM input
ORDERBY id
Row 3 has no Other, so the total is just its value, 0.125.
Value
Other
Result
2.5
4
6.5
−2.5
−3
−5.5
0.13
0.13
−0.4
−1
−1.4
3.75
8
11.75
2
2
0
0.5
0.5
16
16
32
✓ The Tableau formula and the SQL return the same 8 rows.
Where does a straight translation go wrong?
Common mistake
Why does wrapping the sum in coalesce lose values?
In SQL a null in either field makes the whole sum null, and coalescing afterwards turns that into 0. Rows 3 and 6 become 0 instead of 0.125 and 2. Replace each field's null before adding, as ZN does.
Tableau
ZN([Value]) +ZN([Other])
Tempting SQL
SELECTcoalesce(Value + Other, 0) AS result
FROM input
ORDERBY id
SQL that matches
SELECTcoalesce(Value, 0) +coalesce(Other, 0) AS result
FROM input
ORDERBY id
Value
Other
Tableau
Tempting SQL
SQL that matches
2.5
4
6.5
6.5
6.5
−2.5
−3
−5.5
−5.5
−5.5
0.13
0.13
0
0.13
−0.4
−1
−1.4
−1.4
−1.4
3.75
8
11.75
11.75
11.75
2
2
0
2
0
0.5
0.5
0.5
0.5
16
16
32
32
32
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
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
SELECTZEROIFNULL(Value) AS result
FROM input
ORDERBY id