// strings reference

SQL SUBSTRING function

Returns a slice of a string by position. Every engine counts from 1, but the name (SUBSTRING or SUBSTR), the optional length and the meaning of a negative start all vary.

类别
Strings
Returns
string
In this category
2 of 172

语法

SUBSTRING(string, start [, length])
SUBSTRING(string FROM start FOR length)
SUBSTR(string, start [, length])

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

引擎支持

引擎Support备注
SQL Server 是 length is required before SQL Server 2025
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite 是 SUBSTR, and SUBSTRING from 3.34
Oracle Different name or syntax SUBSTR only; there is no SUBSTRING

示例

SQL Server

-- also PostgreSQL, MySQL and SQLite; Oracle spells it SUBSTR
SELECT SUBSTRING('2026-08-01', 1, 4) AS year;  -- 2026

PostgreSQL

SELECT SUBSTRING('abcdef' FROM 2 FOR 3) AS mid;  -- bcd

Oracle

SELECT SUBSTR('abcdef', -3) AS tail FROM dual;  -- def

值得了解

  • Positions are 1-based. Start 0 is not an error but differs: SUBSTRING('abc', 0, 2) is 'a' on SQL Server, PostgreSQL and SQLite (position 0 eats one of the two characters), '' on MySQL, and 'ab' on Oracle, which treats 0 as 1.
  • SQL Server required all three arguments until SQL Server 2025 made length optional. PostgreSQL, MySQL, SQLite and Oracle let you omit length to take the rest of the string.
  • A negative start counts from the end on MySQL, SQLite and Oracle: SUBSTR('abcdef', -3) is 'def'. On SQL Server and PostgreSQL it is a position before the string, so SUBSTRING('abcdef', -2, 4) is just 'a'.

Questions about SUBSTRING / SUBSTR

Is SUBSTRING 0-based or 1-based?

1-based in every major engine. Position 0 does not raise an error, but the result differs by engine: one character short on SQL Server, PostgreSQL and SQLite, empty on MySQL, unchanged on Oracle.

Why does my SUBSTRING need three arguments on SQL Server?

Before SQL Server 2025, SUBSTRING required both start and length; pass LEN(s) as the length to take the rest. SQL Server 2025, PostgreSQL, MySQL, SQLite and Oracle all accept the two-argument form.

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.