Full answer
sql
WITH p(path) AS (VALUES ('/api/v2/users'), ('/health')),
s AS (SELECT path, SUBSTR(path, 2) AS rest1 FROM p),
t AS (SELECT path, CASE WHEN INSTR(rest1, '/') > 0 THEN SUBSTR(rest1, INSTR(rest1, '/') + 1) END AS rest2 FROM s)
SELECT path,
CASE WHEN INSTR(rest2, '/') > 0 THEN SUBSTR(rest2, 1, INSTR(rest2, '/') - 1) ELSE rest2 END AS segment2
FROM t ORDER BY path;| path | segment2 |
|---|---|
| /api/v2/users | v2 |
| /health | NULL |
INSTR only finds the first occurrence, so each step strips what has been read and searches the rest. rest1 drops the leading slash, rest2 drops the first segment, and the final SUBSTR cuts at the next slash. When no slash follows, as in /health, the CASE returns NULL.
PostgreSQL:
sql
SELECT path, SPLIT_PART(path, '/', 3) AS segment2
FROM (VALUES ('/api/v2/users'), ('/health')) AS p(path) ORDER BY path;| path | segment2 |
|---|---|
| /api/v2/users | v2 |
| /health | '' |
SPLIT_PART returns an empty string, not NULL, for a missing part. For deep or variable parsing, a recursive CTE or the json_each split shown earlier scales better than more nesting.
sql
WITH p(path) AS (VALUES ('/api/v2/users'), ('/health')),
s AS (SELECT path, SUBSTR(path, 2) AS rest1 FROM p),
t AS (SELECT path, CASE WHEN INSTR(rest1, '/') > 0 THEN SUBSTR(rest1, INSTR(rest1, '/') + 1) END AS rest2 FROM s)
SELECT path,
CASE WHEN INSTR(rest2, '/') > 0 THEN SUBSTR(rest2, 1, INSTR(rest2, '/') - 1) ELSE rest2 END AS segment2
FROM t ORDER BY path;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- INSTR finds only the first occurrence
- Strip and search again to find later occurrences
- PostgreSQL SPLIT_PART takes a part number
- SPLIT_PART returns '' for missing parts
Common mistakes
- Counting the leading empty segment wrongly in SPLIT_PART
- Nesting many INSTR calls in one unreadable expression
Follow-ups
- How would you return every segment as a row?
- How would you get the last segment?
Tips
- Build the expression in steps with a CTE