← Back to SQL, page 21

sql-0417 · Easy fresher

What do substr('database', -4), substr('database', 2, 3) and instr('database', 'a') return in SQLite?

They return 'base', 'ata' and 2. A negative start counts from the end of the string, substr positions start at 1, and instr returns the 1-based position of the first match.

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;
abcd
baseata20

'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