How is the substring function used in SQL?

The SUBSTRING function in SQL is used to extract a substring from a string.

Syntax:
SUBSTRING(string, start, length)

Explanation of Parameters:

  1. string: the string from which to extract a substring.
  2. Starting position of the substring. The index of the starting position starts counting from 1.
  3. Length: The length of the substring to be extracted. If this parameter is omitted, all characters from the starting position to the end of the string will be extracted.

Given a string “Hello, World!”, you can extract a substring from it using the SUBSTRING function.

  1. Extract a substring starting from the 6th character:
    SELECT SUBSTRING(‘Hello, World!’, 6);
    Result: ” World!”
  2. Extract a substring starting from the first character for a length of 5 characters:
    SELECT SUBSTRING(‘Hello, World!’, 1, 5);
    Result will be “Hello”
  3. Extract a substring of the first three characters starting from the 8th character:
    SELECT SUBSTRING(‘Hello, World!’, 8, 3);
    The result is “Wor”.
bannerAds