IF test THEN value [ELSEIF ...] [ELSE default] END returns the value of the first true test. A null test is not true, so a row with a missing value goes to ELSE, or to null when there is no ELSE. SQL's CASE WHEN test THEN value ELSE default END does exactly the same in DuckDB, Snowflake and BigQuery. Keep the test the way Tableau has it: flipping it moves the nulls.
Updated · Checked on the xmetric engine
What is the syntax?
IF<test>THEN<then>[ELSEIF <test2> THEN <then2> ...][ELSE <default>]END
test
a boolean expression.
then
the value when the test is true.
default
optional, the value when no test is true. A null test counts as not true.
Returns the THEN value of the first true test, the ELSE value, or null if no test is true and there is no ELSE.
What does it return, and what is the SQL?
Each example runs on the same 6 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
Which scores pass?
Tableau
IF[Score]>=80THEN'Pass'ELSE'Retake'END
SQL (DuckDB)
SELECTCASEWHEN Score >=80THEN'Pass'ELSE'Retake'ENDAS result
FROM input
ORDERBY id
The missing score on row 4 is not true, so it gets Retake.
Score
Result
92
Pass
80
Pass
50
Retake
Retake
45
Retake
80
Pass
✓ The Tableau formula and the SQL return the same 6 rows.
Where does a straight translation go wrong?
Common mistake
Why does flipping the test pass the missing score?
Rewriting >= 80 THEN Pass as < 80 THEN Retake ELSE Pass looks equivalent, but row 4's null test fails both ways and lands in the other ELSE, Pass.
Tableau
IF[Score]>=80THEN'Pass'ELSE'Retake'END
Tempting SQL
SELECTCASEWHEN Score <80THEN'Retake'ELSE'Pass'ENDAS result
FROM input
ORDERBY id
SQL that matches
SELECTCASEWHEN Score >=80THEN'Pass'ELSE'Retake'ENDAS result
FROM input
ORDERBY id
Score
Tableau
Tempting SQL
SQL that matches
92
Pass
Pass
Pass
80
Pass
Pass
Pass
50
Retake
Retake
Retake
Retake
Pass
Retake
45
Retake
Retake
Retake
80
Pass
Pass
Pass
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
What does IF return without ELSE?
Rows where no test is true come back null. Columns 1 to 6 are the sample rows, by id.
Case
Tableau, then SQL (DuckDB)
1
2
3
4
5
6
no ELSE
IF [Score] >= 80 THEN 'Pass' ENDCASE WHEN Score >= 80 THEN 'Pass' END
Pass
Pass
null
null
null
Pass
✓ 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
SELECTCASEWHEN Score >=80THEN'Pass'ELSE'Retake'ENDAS result
FROM input
ORDERBY id