// strings reference

SQL SUBSTR function

Extracts part of a string starting at a 1-based position, optionally limited to a length.

Catégorie
Strings
Returns
string
In this category
98 of 172

Syntaxe

SUBSTR(str, start)
SUBSTR(str, start, length)

Each block is a separate form. The support table and the examples show which engine takes which.

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax No SUBSTR; spelled SUBSTRING(str, start, length).
PostgreSQL Oui Supported under this name.
MySQL Oui Supported under this name.
SQLite Oui Supported under this name.
Oracle Oui Supported under this name.

Exemples

SQLite

SELECT SUBSTR('2026-11-20', 1, 7) AS year_month;  -- 2026-11

Oracle

SELECT SUBSTR(phone, -4) AS last_four
FROM contacts;

PostgreSQL

SELECT SUBSTR(code, 4, 2) AS region
FROM postcodes;

Bon à savoir

  • Start 0 is not the same as 1 everywhere: Oracle treats 0 as 1 (SUBSTR('abc', 0, 2) is 'ab'), SQLite and PostgreSQL count position 0 against the length ('a'), and MySQL returns an empty string.
  • Negative starts count from the end in Oracle, MySQL and SQLite: SUBSTR('abcdef', -3) is 'def'. PostgreSQL does not; the same call returns 'abcdef'.
  • A zero length returns '' in MySQL, PostgreSQL and SQLite but NULL in Oracle. A negative length is an error in PostgreSQL, NULL in Oracle, '' in MySQL, and in SQLite it returns the characters before the start: SUBSTR('abcdef', 4, -2) is 'bc'.

Questions about SUBSTR

Is SUBSTR different from SUBSTRING?

Same function. SUBSTRING is the standard name and the only one SQL Server accepts; SQLite, Oracle, MySQL and PostgreSQL accept SUBSTR, and all of them except Oracle also accept SUBSTRING.

What does a negative start position mean?

In Oracle, MySQL and SQLite it counts from the end: SUBSTR('abcdef', -3) is 'def'. PostgreSQL treats it as a position before the string, so use RIGHT(s, 3) there.

What happens when the length runs past the end of the string?

You get the characters that exist, with no error: SUBSTR('abc', 2, 99) is 'bc'.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.