RIGHT(string, n) returns the last n characters, or the whole string if it's shorter. DuckDB's right() is the same. Written with substring, the start is length - n + 1; length - n takes one character too many.
Updated · Checked on the xmetric engine
What is the syntax?
RIGHT(string, number)
string
the text.
number
how many characters to keep.
Returns the rightmost number characters. Null if an input is null.
What does it return, and what is the SQL?
Each example runs on the same 7 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
What are the last two characters of each code?
Tableau
RIGHT([Code], 2)
SQL (DuckDB)
SELECTRIGHT (Code, 2) AS result
FROM input
ORDERBY id
B-71 gives 71; X stays X.
Code
Result
A-12-x
-x
B-71
71
C-301-yz-9
-9
a_1
_1
X
X
D-4-y
-y
null
✓ The Tableau formula and the SQL return the same 7 rows.
Where does a straight translation go wrong?
Common mistake
Why does substring(x, length(x) - 2) return three characters?
Positions start at 1, so the last two characters start at length - 1, not length - 2.
Tableau
RIGHT([Code], 2)
Tempting SQL
SELECTsubstring(Code, length(Code) -2) AS result
FROM input
ORDERBY id
SQL that matches
SELECTRIGHT (Code, 2) AS result
FROM input
ORDERBY id
Code
Tableau
Tempting SQL
SQL that matches
A-12-x
-x
2-x
-x
B-71
71
-71
71
C-301-yz-9
-9
z-9
-9
a_1
_1
a_1
_1
X
X
X
X
D-4-y
-y
4-y
-y
null
null
null
✓ 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
SELECTRIGHT (Code, 2) AS result
FROM input
ORDERBY id