Home >Database >Mysql Tutorial >How to use mysql substring() function

How to use mysql substring() function

青灯夜游
青灯夜游Original
2022-06-17 19:17:2110929browse

In mysql, the substring() function is used to intercept a string. It can return a substring of a given length starting from a specific position in the string. The syntax is "SUBSTRING(string,n)", The value of parameter "n" needs to be an integer, used to specify the starting character of the substring, and can be a negative value. If the parameter "n" is a negative value, the position of the substring starts from the nth character at the end of the string, that is, the nth character from the last, rather than the beginning of the string.

How to use mysql substring() function

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

mysql substring() function: intercept a string

The substring() function can intercept a given length from a string starting from a specific position substring and returned. Syntax:

SUBSTRING(s,n,len)

Returns a substring with the same length as len characters from string s, starting at position n.

  • The n parameter is an integer, used to specify the starting character of the substring, n can be a negative value.

    If n is a positive value, the SUBSTRING function extracts a substring from the beginning of the string. See the following string. How to use mysql substring() function

    If n is a negative value, the position of the substring starts from the nth character at the end of the string, that is, the nth character from the last, rather than the beginning of the string.

  • The len parameter can be omitted, specify the substring length

substring() function usage example

1. The len parameter is omitted

Get the substring from the "MySQL SUBSTRING" string: "SUBSTRING", the position of the substring must start from 7

mysql> SELECT SUBSTRING('MYSQL SUBSTRING', 7);

How to use mysql substring() function

Please note that if the n parameter is zero, the SUBSTRING function returns an empty string:

mysql> SELECT SUBSTRING('MYSQL SUBSTRING', 0);

How to use mysql substring() function

mysql> SELECT SUBSTRING('MySQL SUBSTRING', -10);

How to use mysql substring() function

2. Do not omit the len parameter

mysql> SELECT SUBSTRING('MySQL SUBSTRING',1,5);

How to use mysql substring() function

[Related recommendations: mysql video tutorial

The above is the detailed content of How to use mysql substring() function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn