Tableau function String

Tableau LEFT to SQL

LEFT(string, n) returns the first n characters, or the whole string if it's shorter. DuckDB's left() is identical. If you write it as substring, start at 1: substring(x, 0, n) returns one character fewer.

Updated · Checked on the xmetric engine

What is the syntax?

LEFT(string, number)
string
the text.
number
how many characters to keep.

Returns the leftmost number characters of string. Null if either 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 first three characters of each code?

Tableau

LEFT([Code], 3)

SQL (DuckDB)

SELECT LEFT (Code, 3) AS result
FROM input
ORDER BY id

A-12-x gives A-1; X is shorter and stays X.

CodeResult
A-12-xA-1
B-71B-7
C-301-yz-9C-3
a_1a_1
XX
D-4-yD-4
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, 0, 3) return two characters?

DuckDB strings start at position 1. A start of 0 counts a position before the first character, so the length of 3 covers only two real ones.

Tableau

LEFT([Code], 3)

Tempting SQL

SELECT substring(Code, 0, 3) AS result
FROM input
ORDER BY id

SQL that matches

SELECT LEFT (Code, 3) AS result
FROM input
ORDER BY id
CodeTableauTempting SQLSQL that matches
A-12-xA-1A-A-1
B-71B-7B-B-7
C-301-yz-9C-3C-C-3
a_1a_1a_a_1
XXXX
D-4-yD-4D-D-4
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 LEFT (Code, 3) AS result
FROM input
ORDER BY id

Snowflake documentation

BigQuery

SELECT LEFT (Code, 3) AS result
FROM input
ORDER BY id

BigQuery documentation

What does your own LEFT 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 LEFT?

What if n is longer than the string?

You get the whole string. LEFT([Code], 3) on X is X.

Does LEFT count characters or bytes?

Characters. LEFT([Name], 3) on Café Nord is Caf; DuckDB left() counts characters as well.

Where is this documented?