Menu

SQLite substr(): Extract Text with Positive and Negative Positions

Updated on

SQLite substr(string, start, length) extracts part of a string. Positions are 1-based, not 0-based. The third argument is optional; without it, SQLite returns the text from the starting position to the end.

Use substr() for tasks such as extracting a prefix, getting the last few characters, or selecting a segment of a text field.

Syntax

substr(X, Y)
substr(X, Y, Z)
  • X is the source string or BLOB.
  • Y is the start position. 1 means the first character; a negative value counts back from the end.
  • Z is the optional length. A positive length selects that many characters; a negative length selects characters preceding the start position.
  • If a required argument is SQL NULL, the result is NULL.
  • For text, positions count Unicode characters; when X is a BLOB, positions and lengths count bytes.

Examples

Extract the first three characters

SELECT substr('SQLite', 1, 3) AS prefix;
prefix
------
SQL

Extract from a position to the end

SELECT substr('hello world', 7) AS word;
word
-----
world

Count backwards from the end

SELECT
    substr('abcdef', -3, 2) AS from_end,
    substr('abcdef', 3, -2) AS before_start;
from_end  before_start
--------  ------------
de        ab

The second result may be surprising: a negative length selects text preceding the start position, not text from a negative position toward the end.

Count Unicode characters, not UTF-8 bytes

SELECT
    substr('café', 4, 1) AS character_four,
    length('café') AS characters;
character_four  characters
--------------  ----------
é               4

Do not use the returned character positions as UTF-8 byte offsets in application code.

substr() versus substring()

Starting with SQLite 3.34.0, substring(X,Y,Z) is an alias for substr(X,Y,Z). They produce the same result:

SELECT substr('SQLite', 1, 3) AS short_form,
       substring('SQLite', 1, 3) AS long_form;
short_form  long_form
----------  ---------
SQL         SQL

Use substr() if you also target SQLite versions older than 3.34.0. Function syntax and indexing rules vary among SQL database engines, so check your target dialect before copying an expression.

Common questions

Is the start index zero-based? No, 1 selects the first character. For readable code, use positive positions or negative offsets from the end.

Does substr() return NULL when a match is not found? It is not a search function; it extracts from a position. Use instr() to locate a substring first.

Can it extract from BLOBs? Yes. SQLite counts bytes rather than characters when the input is a BLOB.

See the official SQLite scalar function reference. Test and modify these examples in SQLite Playground.