SUBSTRING_INDEX

SUBSTRING_INDEX is a SQL function that returns a substring from a string before a specified number of occurrences of the delimiter. The substring is the part of the string that comes before the nth occurrence. It allows for extraction of segments from a string based on delimiters and occurrence.

SUBSTRING_INDEX(str, delim, count)

  • str: This represents the source string from which a substring is to be extracted.
  • delim: This refers to the delimiter which is used to divide the source string. It identifies the boundary between sequential units in the string.
  • count: This denotes the number of occurrences of the delimiter in the source string. If the value of count is positive, everything to the left of the final delimiter (counting from the left) is returned. If the value of count is negative, everything to the right of the final delimiter (counting from the right) is returned.

Example

SELECT SUBSTRING_INDEX('www.google.com', '.', 2);

Output

'www.google'

Explanation

In this example, the SUBSTRING_INDEX() function is used to return a substring from a string before counting a specified number of delimiter occurrences. The string ‘www.google.com’ is used as the input, ’.’ is specified as the delimiter and 2 as the count. Consequently, this results in ‘www.google’.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.