// SQL snippet

Find the position of the nth occurrence of a substring in SQL

Parsing fixed-format codes ('AA-BB-CC-DD') means finding the second or third delimiter, not the first.

Main statement
Oracle
Deckt außerdem ab
PostgreSQL MySQL

The task

The position of the third delimiter is the anchor for parsing 'AA-BB-CC-DD'. Oracle's INSTR takes an occurrence number directly.

The snippet

Written for Oracle. Versions for PostgreSQL and MySQL are under Variations.

Oracle
SELECT INSTR(code, '-', 1, 3) AS third_dash
FROM parts;

So funktioniert es

INSTR(search, target, start, occurrence) starts at position 1 and returns the position of the nth match, or 0 when there is no nth match. SQL Server has no occurrence argument, so there you nest CHARINDEX calls, each starting one past the previous match. MySQL 8 and PostgreSQL 15+ take the same occurrence argument in REGEXP_INSTR (the target is a regex there, so escape metacharacters such as '.').

Variations

MySQL 8+

MySQL
SELECT REGEXP_INSTR(code, '-', 1, 3) AS third_dash
FROM parts;

PostgreSQL 15+

PostgreSQL
SELECT REGEXP_INSTR(code, '-', 1, 3) AS third_dash
FROM parts;

Questions that come up

What does a result of 0 mean?

INSTR and REGEXP_INSTR return 0 when there is no nth occurrence, not NULL. Decide whether 0 should mean 'not present' for your parse; usually you guard with NULLIF(pos, 0) or a CASE.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.