← Back to SQL, page 8

sql-0146 · Medium mid

Given paths like '/api/v2/users', write a query that returns the second path segment ('v2').

Find the second slash by searching the remainder after the first one, then take the text up to the third slash. In SQLite that means nesting INSTR and SUBSTR, which is easiest to read in a CTE that keeps the remainder. PostgreSQL's SPLIT_PART(path, '/', 3) does it in one call, because the leading slash creates an empty first part.

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;
pathsegment2
/api/v2/usersv2
/healthNULL

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;
pathsegment2
/api/v2/usersv2
/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