Friday, December 20, 2024

MySQL SUBSTRING() Function

 The SUBSTRING() function in MySQL is used to extract a portion of a string. It allows you to specify the starting point and optionally the length of the substring to extract.

Syntax:

SUBSTRING(string, start, length)
  • string: The original string from which you want to extract the substring.
  • start: The position where the substring starts. If this value is positive, it counts from the beginning of the string (1 being the first character). If it's negative, it counts from the end of the string.
  • length (optional): The number of characters to extract. If this parameter is omitted, the substring will include all characters from the starting position to the end of the string.

Examples:

  1. Basic Example:

    SELECT SUBSTRING('Hello World', 1, 5);
    

    Output: 'Hello'

    • This extracts 5 characters starting from the 1st character.
  2. Extract from a Specific Position:

    SELECT SUBSTRING('Hello World', 7, 5);
    

    Output: 'World'

    • This extracts 5 characters starting from the 7th character.
  3. Using Negative Start Value:

    SELECT SUBSTRING('Hello World', -5, 5);
    

    Output: 'World'

    • This extracts 5 characters starting from the 5th character from the end of the string.
  4. Without the Length Parameter:

    SELECT SUBSTRING('Hello World', 7);
    

    Output: 'World'

    • This extracts the substring starting from the 7th character to the end of the string.

Additional Notes:

  • If start is greater than the length of the string, the result will be an empty string.
  • If length is greater than the remaining length of the string from the starting point, it will return the substring up to the end of the string.

Let me know if you'd like more examples or further explanation!

No comments:

Post a Comment