Tableau function String

Tableau RIGHT to SQL

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)

SELECT RIGHT (Code, 2) AS result
FROM input
ORDER BY id

B-71 gives 71; X stays X.

CodeResult
A-12-x-x
B-7171
C-301-yz-9-9
a_1_1
XX
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

SELECT substring(Code, length(Code) - 2) AS result
FROM input
ORDER BY id

SQL that matches

SELECT RIGHT (Code, 2) AS result
FROM input
ORDER BY id
CodeTableauTempting SQLSQL that matches
A-12-x-x2-x-x
B-7171-7171
C-301-yz-9-9z-9-9
a_1_1a_1_1
XXXX
D-4-y-y4-y-y
nullnullnull

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

SELECT RIGHT (Code, 2) AS result
FROM input
ORDER BY id

Snowflake documentation

BigQuery

SELECT RIGHT (Code, 2) AS result
FROM input
ORDER BY id

BigQuery documentation

What does your own RIGHT formula return?

Edit the formula and run it on the 7 sample rows. Fields: [id], [Name], [Code], [Email], [Num].

Runs in your browser on the xmetric engine. Nothing is uploaded.

Which functions go with it?

What do people ask about RIGHT?

What if n is longer than the string?

You get the whole string: RIGHT([Code], 10) on B-71 is B-71.

How do I drop the last two characters instead?

LEFT([Code], LEN([Code]) - 2); in SQL, left(Code, length(Code) - 2).

Where is this documented?