// strings reference

SQL SUBSTRING_INDEX function

Returns everything before (positive count) or after (negative count) the nth occurrence of a delimiter.

카테고리
Strings
Returns
string
In this category
104 of 172

구문

SUBSTRING_INDEX(str, delim, count)
SUBSTRING_INDEX(str, delim, -count)

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

엔진 지원

엔진Support메모
SQL Server Not built in No equivalent; LEFT/RIGHT with CHARINDEX, or STRING_SPLIT with ordinal.
PostgreSQL Not built in No equivalent; SPLIT_PART returns a single element.
MySQL 예 Supported under this name.
SQLite Not built in No equivalent; INSTR arithmetic with SUBSTR.
Oracle Not built in No equivalent; REGEXP_SUBSTR with occurrence counts.

예시

MySQL

SELECT SUBSTRING_INDEX('www.example.com', '.', 2) AS part;  -- www.example

MySQL

SELECT SUBSTRING_INDEX(email, '@', -1) AS domain
FROM users;

알아 두면 좋은 정보

  • A positive count keeps the part before the nth delimiter, a negative count the part after the nth delimiter from the right: SUBSTRING_INDEX('a.b.c', '.', 2) is 'a.b', SUBSTRING_INDEX('a.b.c', '.', -2) is 'b.c'.
  • When the delimiter occurs fewer than count times, the whole string comes back; there is no NULL or error to signal the shortfall.
  • The delimiter match is case-sensitive even under a case-insensitive collation: SUBSTRING_INDEX('aXbxc', 'x', 1) is 'aXb'.

Questions about SUBSTRING_INDEX

How do I get the third element of a delimited string?

Nest two calls: SUBSTRING_INDEX(SUBSTRING_INDEX(str, ',', 3), ',', -1). If the string has fewer than three elements this returns the last element, not an empty string.

What is the PostgreSQL equivalent?

SPLIT_PART(str, ',', 3) returns the third element directly, or an empty string when it does not exist. From PostgreSQL 14 a negative position counts from the end.

What happens when the delimiter is missing?

SUBSTRING_INDEX returns the entire string for positive and negative counts alike. Check LOCATE(delim, str) > 0 first when a missing delimiter matters.

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.