MID(string, start, [length]) returns the characters from start (counting from 1), up to length of them, or to the end when length is left out. DuckDB's substring(string, start, length) uses the same 1-based start. Starting at 0, as in SQL Server or Python habits, loses a character.
Updated · Checked on the xmetric engine
What is the syntax?
MID(string, start, [length])
string
the text.
start
the 1-based position of the first character to return.
length
optional; how many characters. Left out, MID returns the rest of the string.
Returns the part of string from position start, at most length 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 characters 2 to 4 of each code?
Tableau
MID([Code], 2, 3)
SQL (DuckDB)
SELECTsubstring(Code, 2, 3) AS result
FROM input
ORDERBY id
A-12-x gives -12.
Code
Result
A-12-x
-12
B-71
-71
C-301-yz-9
-30
a_1
_1
X
D-4-y
-4-
null
✓ The Tableau formula and the SQL return the same 7 rows.
Where does a straight translation go wrong?
Common mistake
Why does starting at 0 return one character fewer?
Position 0 sits before the first character, so substring(Code, 0, 3) covers only two. MID counts from 1; translate the start unchanged.
Tableau
MID([Code], 1, 3)
Tempting SQL
SELECTsubstring(Code, 0, 3) AS result
FROM input
ORDERBY id
SQL that matches
SELECTsubstring(Code, 1, 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.
What happens when the length is left out?
MID then runs to the end of the string, like substring with two arguments. Columns 1 to 7 are the sample rows, by id.
Case
Tableau, then SQL (DuckDB)
1
2
3
4
5
6
7
no length
MID([Code], 3)substring(Code, 3)
12-x
71
301-yz-9
1
4-y
null
✓ 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
SELECTSUBSTR(Code, 2, 3) AS result
FROM input
ORDERBY id