Full answer
sql
SELECT substr('database', -4) AS a, substr('database', 2, 3) AS b, instr('database', 'a') AS c, instr('database', 'z') AS d;| a | b | c | d |
|---|---|---|---|
| base | ata | 2 | 0 |
'database' has eight characters. Starting four from the end gives 'base'. Starting at position 2 and taking three characters gives 'ata'. The first 'a' is at position 2, so instr returns 2, and a missing substring returns 0, as the fourth column shows. PostgreSQL's substr does not accept negative starts the same way; use right('database', 4) there, and strpos instead of instr. SQLite 3.34 and later also accept substring as an alias (PostgreSQL behaviour stated, not run here).
sql
SELECT substr('database', -4) AS a, substr('database', 2, 3) AS b, instr('database', 'a') AS c, instr('database', 'z') AS d;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- substr positions start at 1
- Negative start counts from the end in SQLite
- instr returns 0 when not found
- PostgreSQL uses right() and strpos()
Common mistakes
- Using 0-based positions
Follow-ups
- How would you extract the text after the last '/'?
- How would you count occurrences of a character?
Tips
- Count positions from 1