Friday, December 20, 2024

MySQL SUBSTR() Function

 The SUBSTR() function in MySQL is used to extract a substring from a given string. It allows you to return a part of the string starting from a specified position, and optionally, you can specify the length of the substring.

Syntax:

SUBSTR(string, start_position, length)
  • string: The input string from which the substring is to be extracted.
  • start_position: The position from which the substring extraction starts. The position is 1-based, meaning the first character is at position 1.
  • length (optional): The number of characters to extract. If this is omitted, it will return the substring from the start position to the end of the string.

Examples:

  1. Extracting a substring from a string:

    SELECT SUBSTR('Hello, World!', 8, 5);
    

    Result: 'World' Explanation: This extracts 5 characters starting from position 8 (the letter "W").

  2. Extracting substring with no length specified:

    SELECT SUBSTR('Hello, World!', 8);
    

    Result: 'World!' Explanation: This extracts all characters from position 8 to the end of the string.

  3. Using negative start_position:

    SELECT SUBSTR('Hello, World!', -6, 5);
    

    Result: 'World' Explanation: If you use a negative number for start_position, MySQL starts counting from the end of the string. Here, it starts 6 characters from the end of the string.

  4. Extracting from the beginning of a string:

    SELECT SUBSTR('Hello, World!', 1, 5);
    

    Result: 'Hello' Explanation: This extracts the first 5 characters from the string.

Notes:

  • If the start_position exceeds the length of the string, MySQL will return an empty string.
  • If length is negative, MySQL will return the substring starting from the start_position and extending in reverse.

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

No comments:

Post a Comment