FINDNTH(string, substring, n) returns the 1-based position of the nth occurrence, or 0 when there are fewer than n. DuckDB has no FINDNTH: split on the substring, rejoin the first n pieces, and the position is that length plus 1. Guard the case with fewer pieces, or the SQL invents a position past the end.
Updated · Checked on the xmetric engine
What is the syntax?
FINDNTH(string, substring, occurrence)
string
the text to search.
substring
the text to find.
occurrence
which match to return, counting from 1.
Returns an integer: the 1-based position of that occurrence, 0 if there are fewer, 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.
Where is the second hyphen in each code?
Tableau
FINDNTH([Code], '-', 2)
SQL (DuckDB)
SELECTCASEWHENlen(string_split(Code, '-')) >2THENlength(array_to_string(list_slice(string_split(Code, '-'), 1, 2), '-')) +1WHEN Code ISNOTNULLTHEN0ENDAS result
FROM input
ORDERBY id
A-12-x has its second hyphen at 5; B-71 has only one, so the result is 0.
Code
Result
A-12-x
5
B-71
0
C-301-yz-9
6
a_1
0
X
0
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 the split SQL return a position for B-71?
With one hyphen, the first two pieces are the whole string, and its length plus 1 points past the end. Tableau returns 0. Check that there are more than n pieces first.
Tableau
FINDNTH([Code], '-', 2)
Tempting SQL
SELECTlength(array_to_string(list_slice(string_split(Code, '-'), 1, 2), '-'))
+1AS result
FROM input
ORDERBY id
SQL that matches
SELECTCASEWHENlen(string_split(Code, '-')) >2THENlength(array_to_string(list_slice(string_split(Code, '-'), 1, 2), '-')) +1WHEN Code ISNOTNULLTHEN0ENDAS result
FROM input
ORDERBY id
Code
Tableau
Tempting SQL
SQL that matches
A-12-x
5
5
5
B-71
0
5
0
C-301-yz-9
6
6
6
a_1
0
4
0
X
0
2
0
D-4-y
4
4
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
SELECTREGEXP_INSTR(Code, '-', 1, 2) AS result
FROM input
ORDERBY id