MySQL: SUBSTRING Function

  • Post author:
  • Post category:MySQL
  • Post comments:1 Comment
MySQL SUBSTRING Function

In this guide, we will explain how to use the MySQL SUBSTRING function with syntax and examples.

Description

The MySQL SUBSTRING function allows you to extract a substring from a string.

Syntax

The syntax for the SUBSTRING function in MySQL is:

SUBSTRING( string, start_position, [ length ] )

OR

SUBSTRING( string FROM start_position [ FOR length ] )

Parameters or Arguments

string

The source string.

start_position

The position for extraction. The first position in the string is always 1.

length

Optional. It is the number of characters to extract. If this parameter is omitted, the SUBSTRING function will return the entire remaining string.

Note

  • The first position in string is 1.
  • If start_position is a positive number, then the SUBSTRING function starts from the beginning of the string.
  • If start_position is a negative number, then the SUBSTRING function starts from the end of the string and counts backwards. Negative values for start_position was introduced in MySQL 4.1.
  • The SUBSTR function and the MID function are synonyms of the SUBSTRING function.

Applies To

The SUBSTRING function can be used in the following versions :

  • MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23

Example

Let’s look at some SUBSTRING function examples and explore how to use the SUBSTRING function.

For example:

mysql> SELECT SUBSTRING('Adglob.in', 5);
Result: 'ob.in'

mysql> SELECT SUBSTRING('Adglob.in' FROM 5);
Result: 'ob.in'

mysql> SELECT SUBSTRING('Adglob.in', 1, 4);
Result: 'Adgl'

mysql> SELECT SUBSTRING('Adglob.in' FROM 1 FOR 4);
Result: 'Adgl'

mysql> SELECT SUBSTRING('Adglob.in', -2, 2);
Result: 'in'

mysql> SELECT SUBSTRING('Adglob.in' FROM -2 FOR 2);
Result: 'in'

Next Topic : Click Here

This Post Has One Comment

Leave a Reply