MySQL

String Function


MySQL offers a wide range of string functions to manipulate and work with text data. These functions allow you to extract, concatenate, transform, and modify strings in various ways.

 

 

1. LENGTH()

The LENGTH() function returns the length of a string, in bytes. Note that for multi-byte character sets, the result may differ from the number of characters.

Syntax:

SELECT LENGTH(string);
 

Example:

SELECT LENGTH('Hello MySQL') AS StringLength;
 

Result:

StringLength
10

 

 

2. CONCAT()

The CONCAT() function concatenates two or more strings into a single string.

Syntax:

SELECT CONCAT(string1, string2, ...);
 

Example:

SELECT CONCAT('Hello', ' ', 'World!') AS ConcatenatedString;
 

Result:

ConcatenatedString
Hello World!

 

 

3. SUBSTRING()

The SUBSTRING() function extracts a substring from a given string. You can specify the starting position and optionally the length of the substring.

Syntax:

SELECT SUBSTRING(string, start_position [, length]);
 

Example:

SELECT SUBSTRING('MySQL Database', 1, 5) AS SubstringResult;
 

Result:

SubstringResult
MySQL

 

 

 

4. UPPER() and LOWER()

  • UPPER(): Converts all characters in a string to uppercase.
  • LOWER(): Converts all characters in a string to lowercase.

Syntax:

SELECT UPPER(string);
SELECT LOWER(string);
 

Example:

SELECT UPPER('mysql') AS UppercaseString, LOWER('MYSQL') AS LowercaseString;
 

Result:

UppercaseStringLowercaseString
MYSQLmysql

 

 

5. TRIM()

The TRIM() function removes leading and trailing spaces from a string. You can also specify a specific character to remove.

Syntax:

SELECT TRIM(string);
 

Example:

SELECT TRIM('   Hello MySQL   ') AS TrimmedString;
 

Result:

TrimmedString
Hello MySQL

 

 

 

Summary of Common String Functions

FunctionDescription
LENGTH()Returns the length of a string.
CONCAT()Concatenates two or more strings.
SUBSTRING()Extracts a substring from a string.
UPPER()Converts a string to uppercase.
LOWER()Converts a string to lowercase.
TRIM()Removes leading and trailing spaces.
REPLACE()Replaces occurrences of a substring.
LEFT()Extracts characters from the left side.
RIGHT()Extracts characters from the right side.
INSTR()Returns the position of a substring.
LPAD()Pads the left side of a string.
RPAD()Pads the right side of a string.
REVERSE()Reverses a string.
FORMAT()Formats a number as a string.
ASCII()Returns the ASCII value of the leftmost character.