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)
SELECTLEFT (Code, 3) AS result
FROM input
ORDERBY id
A-12-x gives A-1; X is shorter and stays X.
Code
Result
A-12-x
A-1
B-71
B-7
C-301-yz-9
C-3
a_1
a_1
X
X
D-4-y
D-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
SELECTsubstring(Code, 0, 3) AS result
FROM input
ORDERBY id
SQL that matches
SELECTLEFT (Code, 3) AS result
FROM input
ORDERBY id
Code
Tableau
Tempting SQL
SQL that matches
A-12-x
A-1
A-
A-1
B-71
B-7
B-
B-7
C-301-yz-9
C-3
C-
C-3
a_1
a_1
a_
a_1
X
X
X
X
D-4-y
D-4
D-
D-4
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
SELECTLEFT (Code, 3) AS result
FROM input
ORDERBY id