FIND(string, substring) returns the 1-based position of the first match, and 0 when there is none: DuckDB's strpos() does exactly that. With a start position, FIND still counts from the start of the whole string; strpos(substr(...)) counts from the cut, so add the offset back.
Updated · Checked on the xmetric engine
What is the syntax?
FIND(string, substring, [start])
string
the text to search.
substring
the text to find.
start
optional 1-based position to start searching from. The result still counts from the first character.
Returns an integer: the 1-based position of substring in string, 0 if not found, 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 first hyphen in each code?
Tableau
FIND([Code], '-')
SQL (DuckDB)
SELECTstrpos(Code, '-') AS result
FROM input
ORDERBY id
Position 2 in most codes; 0 where there is no hyphen.
Code
Result
A-12-x
2
B-71
2
C-301-yz-9
2
a_1
0
X
0
D-4-y
2
null
✓ The Tableau formula and the SQL return the same 7 rows.
Where does a straight translation go wrong?
Common mistake
Why does strpos(substr(...)) give a smaller position?
substr cuts the string, so strpos counts from the cut. FIND reports 5 for the second hyphen of A-12-x; the cut string says 3. Add start - 1 back when there is a match.
Tableau
FIND([Code], '-', 3)
Tempting SQL
SELECTstrpos(substr(Code, 3), '-') AS result
FROM input
ORDERBY id
SQL that matches
SELECTCASEWHENstrpos(substr(Code, 3), '-') =0THEN0ELSEstrpos(substr(Code, 3), '-') +2ENDAS result
FROM input
ORDERBY id
Code
Tableau
Tempting SQL
SQL that matches
A-12-x
5
3
5
B-71
0
0
0
C-301-yz-9
6
4
6
a_1
0
0
0
X
0
0
0
D-4-y
4
2
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 search from a start position?
FIND skips the first characters but reports the position in the whole string. Columns 1 to 7 are the sample rows, by id.
Case
Tableau, then SQL (DuckDB)
1
2
3
4
5
6
7
with start
FIND([Code], '-', 3)CASE WHEN strpos(substr(Code, 3), '-') = 0 THEN 0 ELSE strpos(substr(Code, 3), '-') + 2 END
5
0
6
0
0
4
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
SELECTPOSITION('-', Code) AS result
FROM input
ORDERBY id