Calculated field
FINDNTH([label], 'e', 2)
Sample data
| label | quantity | amount | flag |
|---|---|---|---|
| cedar cedar | 65 | 12.8 | True |
| ORCHID-west | 66 | -7.6 | False |
| maple-east | 67 | 0 | null |
| willow north | 68 | 25.3 | True |
| birch-birch | 69 | 4.9 | False |
| pine/south | 70 | -1.2 | null |
| ash | 71 | 9 | True |
| null | null | null | null |
The same calculation as SQL
SELECT CASE WHEN strpos(label,'e')=0 THEN 0 WHEN strpos(substr(label,strpos(label,'e')+1),'e')=0 THEN 0 ELSE strpos(label,'e')+strpos(substr(label,strpos(label,'e')+1),'e') END AS result FROM input
Runs the example above.
SELECT REGEXP_INSTR(label,'e',1,2) AS result FROM input
Written for this dialect; not run here.
SELECT REGEXP_INSTR(label,r'e',1,2) AS result FROM input
Written for this dialect; not run here.
Result
| result |
|---|
| 10 |
| 0 |
| 7 |
| 0 |
| 0 |
| 0 |
| 0 |
| null |
Same rows from the calculation and from the SQL in DuckDB.
Where a naive translation goes wrong
- Replacing FINDNTH with strpos(label,'e') changes the shown values or null handling.
Naive SQL
SELECT strpos(label,'e') AS result FROM input
result 4 9 5 0 0 4 0 null Matches the calculation
SELECT CASE WHEN strpos(label,'e')=0 THEN 0 WHEN strpos(substr(label,strpos(label,'e')+1),'e')=0 THEN 0 ELSE strpos(label,'e')+strpos(substr(label,strpos(label,'e')+1),'e') END AS result FROM input
result 10 0 7 0 0 0 0 null
Signature
FINDNTH(string, string, occurrence)