MySQL String Functions
MySQL ASCII() Function
Main Article :- MySql ASCII() Function
The ASCII()
method returns the ASCII value of a character. It return numeric value of left-most character of the input string.
ASCII() works for 8-bit characters.
The NULL within an ASCII function will return NULL and the function will return 0 If the input string is empty.
Syntax:-
Here is the syntax of the MySQL ASCII() function:
ASCII(Input String)
Parameter Values
Parameter | Description |
---|---|
Input String | Required. The ASCII value should be returned for the Input String's first character. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:
Example 1: This example to return the ASCII value of (Capital) B:
SELECT ASCII('B');
Result:
Here, the input string is B, It returned the ASCII value of B: 66.
Example 2: This example to return the ASCII value of (Small) b:
SELECT ASCII('b');
Result:
Here, the input string is b, It returned the ASCII value of b: 98.
Example 3: In this example, we can use numeric values also with or without single quotes. it'll get you the left side first number's ASCII value.
SELECT ASCII('5');
Result:-
Otherwise, You can write the query like below,
SELECT ASCII(5);
Result:-
From the results you can see that the both return ASCII value of '5' as '53'.
Example 4: When more than one character is entered, the first character's value is will shown:
SELECT ASCII('jp');
Result:-
Here, although the argument is jp, but only returned the ASCII value of j: 106.
Example 5: This example will take the Name column and Age in the STUDENT table and give the ASCII value of the left first character:
Let's take this STUDENT table for the below Example:-
StudentName | StudentAge |
---|---|
Sakunthala | 17 |
Chandra | 9 |
The query Will be like this,
SELECT
ASCII(StudentName) AS AsciiCodeOfFirstChar,
ASCII(StudentAge) AS AsciiCodeOfFirstNumber,
FROM STUDENT;
Result:-
AsciiCodeOfFirstChar | AsciiCodeOfFirstNumber |
---|---|
83 | 49 |
67 | 57 |
From the result, The values of the Name column are Sakunthala and Chandra, As per ASCII function, it takes the left side first-string 'S' ASCII value '83' and 'C' ASCII value '67' will be the output, same as the age column is 17 and 9, and it takes left side first number '1' ASCII value '49' and '9' ASCII value '57' will be the output.
MySQL CHAR_LENGTH() Function
The method CHAR LENGTH()
returns the length of a string (in characters).
The function simply counts the number characters and ignore whether the character(s) are single-byte or multi-byte. Therefore a string containing three 2-byte characters, LENGTH()
function will return 6, whereas CHAR_LENGTH() function will returns 3.
Note: This function is same as CHARACTER_LENGTH() function.
Remember: This function counts the white spaces as a character.
Syntax:-
Here is the syntax of the MySQL CHAR_LENGTH() function:
CHAR_LENGTH(Input String)
Parameter Values
Parameter | Description |
---|---|
Input String | Required. To count the length of the InputString. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: The following MySQL query will count the length of the specified string which is inside brackets:
SELECT CHAR_LENGTH("Simmanchith Tutorial") AS StringLength;
Result:-
StringLength |
---|
20 |
From the above result, the specified String "Simmanchith Tutorial" length is 20. It also counts white spaces between the Input String.
Example 2: This example returns the length of the text in the "Name" and "Continent" columns should be returned:
Let's take this COUNTRY table for the below Example:-
CountryName | Continent |
---|---|
Saint Vincent and the Grenadines | North America |
Georgia | Asia |
The query is,
SELECT
CHAR_LENGTH(CountryName) AS LengthOfName,
CHAR_LENGTH(Continent) AS LengthOfContinent
FROM Customers;
Result:-
LengthOfName | LengthOfContinent |
---|---|
32 | 13 |
7 | 4 |
As you see in the result CountryName column returns LengthOfName "Saint Vincent and the Grenadines" is 14 and "North America" is 10, and the Continent column returns LengthOfContinent "Georgia" is 7 and "asia" is 4.
MySQL CHARACTER_LENGTH() Function
The method CHARACTER_LENGTH()
returns the length of a string (in characters).
Note: CHARACTER_LENGTH() is a synonym for CHAR_LENGTH().
Remember: This function counts the white spaces as a character.
Syntax:
Here is the syntax of the MySQL CHARACTER_LENGTH() function:
CHARACTER_LENGTH(string)
Parameter Values
Parameter | Description |
---|---|
Input string | Required. The length of the Input string to be counted. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: From this example length of the text in the columns should be returned:
Let's take this CUSTOMER table for the below Example:-
CustomerName | CustomerEMail |
---|---|
Sakunthala | Sakunthala3815@yahoo.com |
Bala Murugan | Bala-Murugan9570@gmail.com |
The query will be like this,
SELECT
CHARACTER_LENGTH(CustomerName) AS LengthOfName,
CHARACTER_LENGTH(CustomerEmail) AS LengthOfEmail
FROM Customer;
Result:-
LengthOfName | LengthOfEmail |
---|---|
10 | 24 |
12 | 26 |
Through the result CustomerName column returns LengthOfName "Sakunthala" is 10, "Bala Murugan" is 12, and the CustomerEmail column returns LengthOfEmail "Sakunthala3815@yahoo.com" is 24 and "Bala-Murugan9570@gmail.com" is 26.
Example 2: The example gives the length of the specified input string:
SELECT CHARACTER_LENGTH('Simmanchith Tutorial') AS LengthOfString;
Result:-
lengthofstring |
---|
20 |
The result will give the exact count of the input string 'Simmanchith Tutorial' the output will be 20 including spaces.
MySQL CONCAT() Function
Main Article :- MySql CONCAT() Function
CONCAT()
is a function that Concatenates two or more strings and returns a string..
The output is a nonbinary string if all arguments are nonbinary. The comparable nonbinary string representation of a numeric argument is created.
A binary string is returned if any of the parameters are binary strings.
Note: If any of the arguments are NULL, CONCAT() returns NULL.
Syntax:-
Here is the syntax of MySQL CONCAT() function:
CONCAT(expr1, expr2, expr3,...)
Parameter Values
Parameter | Description |
---|---|
expr1, expr2, expr3, etc. |
Required. The expressions to add together.
Note: It returns NULL if any of the expressions have a NULL value. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: The example Combines the specific string inside the Concat function.
SELECT CONCAT("Simmanchith ", "Tutorial ", "is ", "Useful") AS ConcatenatedString;
Result:-
ConcatenatedString |
---|
Simmanchith Tutorial is Useful |
From the result input strings ("Simmanchith ", "Tutorial ", "is ", "Useful") inside concat function merge into (simmanchith tutorial is useful) single string.
Example 2: This example using Null value in Concat function:
SELECT CONCAT('Simman', NULL, 'chith') AS NullValue;
Result:-
NullValue |
---|
NULL |
You can understand from this output if one NULL value is included in the Concat function the result will be always NULL in MySQL.
Example 3: This Example Combining decimal numbers and numbers through the Concat function:
SELECT CONCAT(14.3, 23, 90);
Result:-
The result can prove that you can concatenate specific numbers, the numbers are also considered as a string by the Concat function.
Example 4: This example performs combining even without the Concat function, It can combine the specific expressions which is inside a quote:
SELECT 'I' 'Love' 'India';
Result:-
The result For the quoted strings, concatenation can be performed by placing the strings next to each other. So the result shows as ILoveIndia.
Example 5: This example Combine the following two columns into a single "CombinedColumns" column:
Let's take this BOOKSIMPLE table for the below Example:-
BookName | BookPrice |
---|---|
Learing Sql Server T-Sql | 60 |
Mastering Oracle SQL | 150 |
The query statement will be,
SELECT
CONCAT(BookName, " ", BookPrice) AS CombinedColumns
FROM BOOKSIMPLE;
Result:-
CombinedColumns |
---|
Learing Sql Server T-Sql 60.00 |
Mastering Oracle SQL 150.00 |
From the above query, the Concat function will merge a number of column values as a string, here BookName, BookPrice Columns are combined into a single String.
MySQL CONCAT_WS() Function
CONCAT WS()
is a special form of CONCAT() that joins two or more expressions with a separator.
The first argument serves as a divider between the others. Between the strings to be concatenated, the separator is placed.
As with the rest of the inputs, the separator can be a string. The result will be NULL if the separator is NULL.
Note: The function CONCAT WS() doesn't avoid over empty strings. It does, however, omit any NULL values following the separator argument.
Syntax:-
Here is the syntax of MySQL CONCAT_WS() function:
CONCAT_WS(divider, string1, string2, ..., stringN)
Parameter Values
Parameter | Description |
---|---|
divider | Required. The divider that must be used between each expression. This method returns NULL if separator is null. |
string1, string2, stringN, etc. |
Required. The phrases that should be combined. If there is a NULL value in string1, string2, ..., stringN, it will be ignored by CONCAT_WS(). |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: Let's use this example to Combine numerous phrases and divide them with a "-" separator:
SELECT CONCAT_WS("-", "Simmanchith", "Tutorial", "is", "Useful") AS MergedString;
Result:-
MergedString |
---|
Simmanchith-Tutorial-is-Useful |
This result is a "-" divider, which is added between every string.
Example 2: The example of CONCAT_WS() function ignores the NULL value parameter. See the example below:
SELECT CONCAT_WS('-', 'Welcome', NULL, 'Learner');
Results:-
Through the result, you can see that separator is inserted between each string value.
Example 3: Use this example to Integrate the five columns listed below into one "Details" column (with a space between them):
Let's take this EMPLOYEEADVANCE table for the below Example:-
Name | Gender | City | Dept | Salary |
---|---|---|---|---|
Harish Karthik | Male | Mysore | Security | 31500 |
Chandra | Female | Madurai | Web Design | 32000 |
The query for requirement,
SELECT
CONCAT_WS(" | ", Name, Gender, City, Dept, Salary) AS Details
FROM EMPLOYEEADVANCE;
Result:-
Details |
---|
Harish Karthik | Male | Mysore | Security | 31500.00 |
Chandra | Female | Madurai | Web Design | 32000.00 |
From the result, concat_ws function is used to merge the Name, Gender, City, Dept, and Salary columns using " | " this separator.
MySQL FIELD() Function
In MySQL, the FIELD()
function returns the index (position) location of a string in a list of strings.
This function searches with no regard for case.
Note: If the specified value sometimes doesn't exist in the list of values, this function returns 0. If the value is NULL, this function returns 0, because NULL fails equality comparison with any value.
FIELD() compares all parameters as strings if they are all strings. When all of the reasons are numerical, they are evaluated numerically. The arguments are otherwise evaluated by comparing as double.
Note: FIELD() is the complement of ELT()
.
Syntax:-
Here is the syntax of MySQL FIELD() function:
FIELD(string, str1, str2, ..., strN)
Parameter Values
Parameter | Description |
---|---|
str | Required. The string looks for match in the list. |
str1, str2, str3, .... | Required. The list of strings. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: This example Return the index for the position of "j" in the string list:
SELECT FIELD("j", "a", "n", "j");
Result:-
From the result, the searched string j was compared to the remaining list of strings, The string j was found in 3rd position.
Example 2: In this example, let's see if there is no matching available in the list:
SELECT FIELD("c", "a", "b");
Result:-
As per the result, you can see that if there is no matching string available in the list the result will be 0.
Example 3: In the before examples, the small letter compares to the small letter, here we use Capital letters to compare small letters:
SELECT FIELD("A", "v", "a", "p");
Result:-
This result shows that the searching string "A", compares to the remaining string in the lists. after the comparison small letter "a" is found in the 2nd position.
Example 4: In previous examples string values were used for comparison, this example used numeric values, to return the 9th index position:
SELECT FIELD(9, 5, 7, 0, 9, 4, 3);
Result:-
From the result, Number 9, is found at 4th place.
Example 5: In this case, the FIELD() function returns 0 if the value is NULL:
SELECT FIELD(NULL, 'J', 'P', NULL);
Result:-
if we mention null as a matching string 0 will be the output.
MySQL FIND_IN_SET() Function
The FIND_IN_SET()
method finds a string within a list of strings and returns its location.
If the string in the string list has N substrings, it returns a value in the range of 1 to N.
A string list is made up of substrings separated by, characters. The FIND_IN_SET() function is optimised to use bit arithmetic if the first argument is a persistent string and the second is a column of type SET
.
If the string in stringlist is the empty string, returns 0. If either argument is NULL, this function returns NULL.
Remember: This function does not work properly if the first argument contains a comma (,) character.
Syntax:
Here is the syntax of MySQL FIND_IN_SET() function:
FIND_IN_SET(string, string_list)
Parameter Values
Parameter | Description |
---|---|
string | Required. The string to search for limit. |
string_list | Required. The string values to search for specific range(separated by commas). |
Return Values
- If string list contains string, the function will return the position number.
- If string list does not contain a string, the function returns 0.
- If the string is NULL, the function returns NULL.
- If string list is null, the function will return 0.
- The function will return NULL if string list is NULL.
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:
Example 1: This example search for "m", Within the list of strings:
SELECT FIND_IN_SET("m", "d,a,m");
Result:
In the result, the string "m" searched in the stringlist was found at 3rd postion.
Example 2: In this example, searching for string which is not Within the list of strings:
SELECT FIND_IN_SET("a", "m,o,m");
Result:-
Here we search for "a" in the string list, but it is not available in the list so the output is 0.
Example 3: In this example we search for string with empty stringlist, null value with list of strings, string with null value.
SELECT
FIND_IN_SET('Y', ''),
FIND_IN_SET(NULL, 'S,K,A'),
FIND_IN_SET('Y', NULL);
Result:-
find_in_set('Y', '') | find_in_set(NULL, 'S,K,A') | find_in_set('Y', NULL) |
---|---|---|
0 | NULL | NULL |
From the result you could see, firstly string "Y" looking for in the string list no matching there so it returns 0, The second Null value searched in the string list, returns Null. Now string compares to Null, it returns Null.
MySQL FORMAT() Function
Main Article :- MySql FORMAT() Function
The FORMAT()
function Format the number to a format like '#,###,###.##' a number to a string format, then round it to a specified number of decimal places, and it returns the result as a string.
Syntax:
Here is the syntax of MySQL FORMAT() function:
FORMAT(numeric value, decimal_places, locale)
Parameter Values
Parameter | Description |
---|---|
numeric value | Required. formatted number. |
decimal_places | Required. The number of decimal places that can be used to express a number. If this option is chosen to 0, the function delivers a string with no decimal places. |
locale | Optional. establishes the thousand separators and their grouping. MySQL will use en_US by default if you don't specify a locale operator. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: The number should be formatted as "#,###,###.##" in this case (and rounded to two decimal places):
SELECT FORMAT(459582.6789, 3);
Result:
As per the result, the decimal point 459582.6789 was rounded to 459,582.689 based on the specified numeric value.
Example 2: This example Format the number in the following format: "#,###,###.##" (rounding to 0 decimal places):
SELECT FORMAT(250500.5634, 0);
Result:
Through the result, you can see that we didn't pass numeric values so the actual decimal rounding will be performed.
Example 3: The following statement uses the de_DE locale instead of the en_US locale:
SELECT FORMAT(4532.3,4,'de_DE');
Result:
The de_DE locale uses a dot (.) for thousand grouping and a comma (,) for decimal mark, as shown in the output.
MySQL INSERT() Function
The INSERT()
method in MySQL replaces a substring with a new string based on its start position and specified amount of characters.
Returns NULL if any argument is NULL.
Note: This function is multibyte safe.
Syntax
Here is the syntax of MySQL INSERT() function:
INSERT(str, state, num, str2)
Parameter Values
Parameter | Description |
---|---|
str | Required. The text that will be changed. |
position | Required. The state where to insert string2 |
number | Required. The set of characters to replace. |
new str | Required. The string to insert into string. |
Return Values
- If state is longer than the length of the string, the original string is returned.
- If number is greater than the length of the rest of the string, this function substitutes string from position to the end.
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: From this example the string "simmanchith.com", add the term "Learners". The first eleven characters must be replaced :
SELECT INSERT(simmanchith.com", 1,11, "Learners");
Result:
As per the result, the website simmanchith contains 11 characters so the position range is selected from 1 to 11, and the "simmanchith" string is replaced by "Learners".
Example 2: We replaced the first 11 characters in the previous example, now let's replace the last three characters:
SELECT INSERT("simmanchith.com", 11, 3, "in");
Result:
The simmanchith.com string as per mentioned position 11, 3 the last 3 characters "com" will replace into new string "in".
Example 3: If any of the arguments are NULL, the method returns NULL:
SELECT
INSERT(NULL, 7, 1, ' ') NullOne,
INSERT('Simman_chith', NULL, 1, ' ') NullTwo,
INSERT('Simman_chith', 7, NULL, ' ') nullThree,
INSERT('Simman_chith', 7, 1, NULL) NullFour;
Result:-
NullOne | NullTwo | NullThree | NullFour |
---|---|---|---|
NULL | NULL | NULL | NULL |
As per result if there is a null value in the function the output will be null.
MySQL INSTR() Function
The INSTR() function returns the location of the first occurrence of a string within another string.
This function is case-sensitive only if at least one argument is a binary string.
With two parameters, the INSTR() method is identical to the POSITION()
and LOCATE()
functions.
Syntax:
Here is the syntax of MySQL INSTR() function:
INSTR(str, substr)
Parameter Values
Parameter | Description |
---|---|
str | Required. Searching string. |
substr | Required. str is the searching string here. If substr could not be discovered, this method returns 0. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1:This example searches for str "h" matching state in string "simmanchith.com":
SELECT INSTR("simmanchith.com", "h") AS MatchingState;
Result:
MatchingState |
---|
8 |
The str "h" search for matching string in the substr value "simmanchith.com" and matching position was found at 8 in the example.
Example 2: Return to its original location by searching for "COM" in the text "simmanchith.com" :
SELECT INSTR("simmanchith.com", "COM") AS MatchingState;
Result:
MatchingState |
---|
13 |
From the result, the matching string "COM" was found at the 13th state in the text "simmanchith.com".
Example 3: This example to Find "M" in the EmployeeName column and return the following position:
Let's take EMPLOYEESIMPLE table to perform this task:
Name | Dept |
---|---|
Bala Murugan | Programming |
Ranjani Mai | Administration |
The query will be,
SELECT
EmployeeName, INSTR(Name, "M") as FoundAt
FROM EMPLOYEESIMPLE;
Result:
EmployeeName | FoundAt |
---|---|
Bala Murugan | 6 |
Ranjani Mai | 9 |
In this example, search for the "M" string available in the "EmployeeName" column, the EmployeeName wise In the name "Bala Murugan", the search string "M" was found at the 6th position. Using the same method, in the employee name "Ranjani Mai", the search string "M" was found at the 9th position.
MySQL LCASE() Function
The LCASE()
function in MySQL transforms and returns the provided string in lowercase.
Note:The LCASE() function and the LOWER()
function are interchangeable.
Syntax
Here is the syntax of MySQL LCASE() function:
LCASE(str)
Parameter Values
Parameter | Description |
---|---|
str | Required. The conversion string. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: As an example, Convert the case of the string to lowercase:
SELECT LCASE("Simmanchith Tutorial is USEFUL");
Result:
Using this string "Simmanchith Tutorial is USEFUL" inside the function is converted to lowercase.
Example 2: When we use Null value in this example:
SELECT LCASE(NULL);
Result:
When the str parameter value is NULL, the function returns NULL.
Example 3: In this example text in "BookName" column transform into lowercase:
let's take this BOOKADVANCE to execute the function:
BookName | Domain |
---|---|
SQL Functions Reference | Performance |
Understanding the New SQL | Performance |
The query will be,
SELECT BookName,
LCASE(BookName) AS LowercaseBookName
FROM BOOKADVANCE;
Result:
BookName | LowercaseBookName |
---|---|
SQL Functions Reference | sql functions reference |
Understanding the New SQL | understanding the new sql |
From the result, BookName columns all data will be changed into lowercase.
MySQL LEFT() Function
Main Article :- MySql LEFT() Function
The LEFT()
method in MySQL returns the string leftmost N characters.
Note: This function starting from left.
Syntax
Here is the syntax of MySQL LEFT() function:
LEFT(str, set_of_charaters)
Parameter Values
Parameter | Description |
---|---|
str | Required. The string to be extracted. |
length | Required. The number of characters that can be extracted to its maximum. If this parameter is greater than the length of string, this method will return string. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: This example Extract the following three characters from a string :
SELECT LEFT("Simmanchith Tutorial", 6) AS StringExtraction;
Result:
StringExtraction |
---|
Simman |
From the result, this function starts at the left and extracts the first 6 leftmost characters.
Example 2: As an illustration, consider the following: The function take value as an empty string if length is zero, negative, or null :
SELECT
LEFT('Welcome', 0),
LEFT('Welcome', -1),
LEFT('Welcome', NULL),
LEFT(NULL, NULL);
Result:
left('welcome', 0) | left('welcome', -1) | left('welcome', null) | left(null, null) |
---|---|---|---|
NULL | NULL |
Through the result, If the function take NULL as input, the output will be NULL, and if the function takes a negative or zero as input, the output will be empty.
Example 3: This illustration Extract the following 5 characters from the text of the "CustomerName" column (starting at the left):
let's take this CUSTOMER to execute the function:
CustomerName | |
---|---|
Azaghu Varshith | Azaghu-Varshith750@yahoo.com |
Sakunthala | Sakunthala8804@hotmail.com |
The query will be,
SELECT
LEFT(Name, 6) AS StringNameExtraction,
LEFT(Email, 10) AS StringEmailExtraction
FROM CUSTOMER;
Result:
StringNameExtraction | StringEmailExtraction |
---|---|
Azaghu | Azaghu-Var |
Sakunt | Sakunthala |
From the result, it takes two columns from the customer table: the CustomerName column extracts the first 6 leftstring, and the Email column extracts the first 10 leftstring.
MySQL LENGTH() Function
Main Article :- MySql LENGTH() Function
The LENGTH()
function calculates the length of a string.
Multibyte character counts as multiple bytes, and the function is measured in bytes. Which means that LENGTH() returns 10 for a string with five 2-byte characters, whereas CHAR_LENGTH()
returns 5.
Note: In MySQL, the Length() OpenGIS geographic function is called ST_Length()
.
Remember: The length function calculate space as a character.
Syntax
Here is the syntax of MySQL LENGTH() function:
LENGTH(str)
Parameter Values
Parameter | Description |
---|---|
str | Required. The String length will be calculated. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:
Example 1: This example calculates length of the specified String:
SELECT LENGTH("Simmanchith Tutorial") AS TotalLengthOfString;
Result:
TotalLengthOfString |
---|
20 |
The length of the input string "Simmanchith Tutorial" is 20 as a result of the calculation.
Example 2: Let's check different characters, positive or negative numbers, null, now, curdate as a string input inside the length function:
SELECT
LENGTH('') AS EmptyLength,
LENGTH(20) AS NumberLength,
LENGTH(-20) AS NegativeNumberLength,
LENGTH(+20) AS PositiveNumberLength,
LENGTH(NOW()) AS NowLength,
LENGTH(CURDATE()) AS CurrentDateLength,
LENGTH(NULL) AS NullLength;
Result:
EmptyLength | NumberLength | NegativeNumberLength | PositiveNumberLength | NowLength | CurrentDateLength | NullLength |
---|---|---|---|---|---|---|
0 | 2 | 3 | 2 | 19 | 10 | NULL |
Explaination:
- LENGTH('') gives you 0, because it's empty. if you put space inside code it will return length based on spaces.
- LENGTH('20') returns 2. Because +20 equals 20, LENGTH(+20) gives us 2.
- LENGTH(-20) gives you 3. This is due to the fact that the matching string for LENGTH(-20) is '-20', and LENGTH('-20') yields 3.
- LENGTH('2022-05-10 08:12:57') is the same as LENGTH(NOW()).
- LENGTH(NULL) gives You null value, because it have no characters.
Example 3: This example return the number of bytes in the "StudentName" column's text:
Let's take "STUDENT" table to execute the query:
StudentName | Gender |
---|---|
Rishi Keshan | Female |
Ranjani Mai | Female |
Ramanathan | Male |
Sakunthala | Male |
The query will be look like,
SELECT
StudentName, LENGTH(StudentName) AS LengthOfStudentName
FROM STUDENT;
Result:
StudentName | LengthOfStudentName |
---|---|
Rishi Keshan | 12 |
Ranjani Mai | 11 |
Ramanathan | 10 |
Sakunthala | 10 |
We got the StudentName column from the result and used the length function to calculate the length of the name in the StudentName column.
MySQL LOCATE() Function
Main Article :- MySql LOCATE() Function | MySql INSTR() Function | MySql POSITION() Function
The LOCATE()
method finds the first instance of a substring in a string.
If the substring cannot be found within the original string, this function returns 0.
The LOCATE() function are case-insensitive. The function is the same as POSITION()
and INSTR()
with two parameters.
Syntax:
Here is the syntax of MySQL LOCATE() function:
LOCATE(substr, str)
or
LOCATE(substring, string, startPos)
Parameter Values
Parameter | Description |
---|---|
substring | Required. The substring to search for in string. |
string | Required. The search string. |
startPos | Optional. The starting point for your search. The default is in the first place. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1:Return position: Search for "a" in the text "simmanchith.com."
SELECT LOCATE("a", "simmanchith.com") AS MatchPosition;
Result:
matchposition |
---|
5 |
This query searching for 'a' in simmanchith.com, the a is found at 5th position.
Example 2: Return position: search for "com" in the text "simmanchith.com" (starting at position 3).
SELECT LOCATE("com", "simmanchith.com", 3) AS MatchPosition;
Result:
MatchPosition |
---|
13 |
The result search string "com" located in the string "simmanchith.com" finds the starting at position 3.
Example 3: This example Find "e" in the BookName column and return the following position:
Let's use BOOKSIMPLE table to execute the example:
BookName | Price |
---|---|
Teach Yourself SQL | 85 |
SQL Fundamentals | 195 |
The query will be look like this,
SELECT
LOCATE("e", BookName) AS LocationFoundAt
FROM BOOKSIMPLE;
Result:
LocationFoundAt |
---|
2 |
11 |
From the BookSimple table, search for the "e" string in the BookName column.
MySQL LOWER() Function
Main Article :- MySql LCASE() Function | MySql LOWER() Function
The LOWER()
method in MySQL returns a lowercase version of the provided string.
The function will NULL return when the string parameter is NULL.
Note: LCASE()
and LOWER()
are the same thing.
Syntax
Here is the syntax of MySQL LOWER() function:
LOWER(String)
Parameter Values
Parameter | Description |
---|---|
String | Required. The string to convert |
Technical Details
Examples:-
Example 1: The illustration Change the case of the text to lowercase:
SELECT LOWER("Simmanchith Tutorial is USEFUL") AS LowerText;
Result:
LowerText |
---|
simmanchith tutorial is useful |
The input string "Simmanchith Tutorial is Useful" gets transformed to lowercase as a result of this.
Example 2: Using NULL value as input string in this example:
SELECT LOWER(NULl);
Result:
When we use the NULL value in lower function it will return NULL.
Example 3: Reduce the capitalization of the text in "CountryName" with this example:
Let's take COUNTRY table to execute the example:
Code | CountryName |
---|---|
ISL | Iceland |
FJI | Fiji Islands |
The query will be like this,
SELECT
LOWER(Code) AS LowercaseCountryCode,
LOWER(CountryName) AS LowercaseCountryName
FROM Country;
Result:
LowercaseCountryCode | LowercaseCountryName |
---|---|
isl | iceland |
fji | fiji islands |
The Lower function is used in this result to transform the columns Code and CountryName to lowercase.
MySQL LPAD() Function
The LPAD()
method in MySQL left pads a string with another string of the given length.
Note: If you want to right pad a string, use the RPAD()
function.
Syntax
Here is the syntax of MySQL LPAD() function:
LPAD(str, len, padstr)
Parameter Values
Parameter | Description |
---|---|
str | Required. This is the first string. If the length argument is longer than the length parameter, this function removes the overfloating characters from the string. |
len | Required. The length of the string after it has been left-padded. |
padstr | Required. left-pad string to string. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: Add "HI" to the left side of the string to make it a total length of 10:
SELECT LPAD("Hello", 10, "HI");
Result:
The length of input string "Hello" is calculated as 5. The length of input length is 10. The padding string "HI" will be added on the left side to satisfy the overall length of 10.
Example 2: Let's use negative number, and null in the lpad function in this example:
SELECT
LPAD('Hello', -1, 'D') AS LpadNegative,
LPAD('NULL', -1, 'U') AS LpadNull;
Result:
LpadNegative | LpadNull |
---|---|
NULL | NULL |
The output will be null if the length is negative. The output will be null if a string is given as null.
Example 3: For instance, to make "EmployeeName" 30 characters long, pad the text with "IND":
Let's take "EMPLOYEESIMPLE" table to execute example:
EmployeeName | Dept |
---|---|
Balan | Security |
Siva Kumar | Web Design |
SELECT
LPAD(EmployeeName, 30, "IND") AS LeftPadEmployeeName
FROM EMPLOYEESIMPLE;
Result:
LeftPadEmployeeName |
---|
INDINDINDINDINDBalan |
INDINDINDISiva Kumar |
From this result, length of input column EmployeeName will be calculated. The length of input length is 20. The padding string "IND" will be added on the left side to satisfy the overall length of 20.
MySQL LTRIM() Function
Using the LTRIM()
method it will returns the string with leading space characters removed.
Note: The function will return NULL, if the parameter is NULL.
Syntax
Here are some examples of MySQL LTRIM() function.
LTRIM(text)
Parameter Values
Parameter | Description |
---|---|
text | Required. Use this string to remove leading spaces from a string. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example : To eliminate leading spaces from a string, follow the steps below:
SELECT LTRIM(" Simmanchith Tutorial") AS TrimmedLeftString;
Result:
TrimmedLeftString |
---|
Simmanchith Tutorial |
From the result, the string has some extra space before the string " Simmanchith Tutorial". After using this function, the extra spaces will be removed.
MySQL MID() Function
The MID()
function in MySQL returns a substring of a given length beginning at the provided location.
Note: The SUBSTRING()
routine is identical to the MID()
and SUBSTR()
routines.
Syntax
Here is the syntax of MySQL MID() function:
MID(str, begin, len)
Parameter Values
Parameter | Description |
---|---|
str | Required. The string to be extracted. |
begin | Required. This is the beginning. It could be positive or negative. If the string starts with a positive number, this method extracts it from the beginning. If the string contains a negative number, this method pulls it from the ending. |
len | Required. The number of characters that need to be extracted. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: To remove a substring from a string, use this example (starting at position 7, remove five characters):
SELECT MID("Simmanchith Tutorial", 7, 5) AS ExtractedString;
Result:
ExtractedString |
---|
chith |
The input string "Simmanchith Tutorial" is used to Extract the result. The string starts at the 7th position, and you specify 5 as a character length and then "chith" will be the result.
Example 2: To remove a substring from a string, use this example (starting at position -8, remove five characters):
SELECT MID("Simmanchith Tutorial", -8, 5) AS ExtractStringReverse;
Result:
ExtractStringReverse |
---|
Tutor |
The input string "Simmanchith Tutorial" is used to extract the result. Here the beginning position is a negative number -8, so the search will begin right to left, because of the specified 5 character length, and then it will return "Tutor".
Example 3: Use this example to remove substring from a EmployeeName column:
Let's take EMPLOYEEADVANCE table to execute the example:
EmployeeName | Dept |
---|---|
Prathap | Security |
Chandra | Programming |
The query will be look like this,
SELECT MID(EmployeeName, 2, 5) AS ExtractEmployeeNameString
FROM EMPLOYEEADVANCE;
Result:
ExtractEmployeeNameString |
---|
rath |
hand |
From the result, the string was extracted from the Employeename column, Starting at position 2, and extracted 5 characters from the text in a column to get an extractemployeename column as output.
MySQL POSITION() Function
The Location()
method returns the first appearance of a substring in a string.
If the substring cannot be located within the original string, this function returns 0.
This function doesn't consider case when searching.
Note:The POSITION() and LOCATE() functions are interchangeable.
Syntax
Here is the syntax of MySQL POSITION() function:
POSITION(substr, str)
Parameter Values
Parameter | Description |
---|---|
substr | Required. In string, the substring to look for. |
string | Required. Searching of the original string. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Examples:-
Example 1: The Return position: Search for "a" in the string "simmanchith.com."
SELECT POSITION("a" IN "simmanchith.com") AS MatchPosition;
Result:
MatchPosition |
---|
5 |
From the result the matching string "a" matched at 5th position.
Example 2: Return position: search for "COM" in string "simmanchith.com"
SELECT POSITION("COM" IN "simmanchith.com") AS MatchPosition;
Result:
MatchPosition |
---|
13 |
Through the result, the whole string "COM" matched at the 11th position in the input string "simmanchith.com".
Example 3: Extracts "e" value from this example:
Let's use BOOKSIMPLE table to execute the example:
BookName | Price |
---|---|
Teach Yourself SQL | 85 |
SQL Fundamentals | 195 |
The query will be look like this,
SELECT
LOCATE("e" IN BookName) AS LocationFoundAt
FROM BOOKSIMPLE;
Result:
LocationFoundAt |
---|
2 |
11 |
From the BookSimple table, search for the "e" string in the BookName column.
MySQL REPEAT() Function
The REPEAT() method repeats a string for the provided number of times.
Syntax
REPEAT(string, number)
Parameter Values
Parameter | Description |
---|---|
string | Required. The string to repeat |
number | Required. The amount of times the string should be repeated. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example:
Repeat a string 3 times:
SELECT REPEAT("SQL Tutorial", 3);
Result
More Examples:
Repeat the text in CustomerName 2 times:
SELECT REPEAT(CustomerName, 2)
FROM Customers;
Result
Ana Trujillo Emparedados y heladosAna Trujillo Emparedados y helados
Repeat the string 0 times:
SELECT REPEAT("SQL Tutorial", 0);
Result
MySQL REPLACE() Function
Main Article :- MySql REPLACE() Function
The REPLACE() method creates a new substring for every instances of a substring within a string.
Note:This method replaces characters in a case-sensitive manner.
Syntax
REPLACE(string, substring, new_string)
Parameter Values
Parameter | Description |
---|---|
string | Required. The original string |
substring | Required. The substring to be replaced |
new_string | Required. The new replacement substring |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example:
Replace "SQL" with "HTML":
SELECT REPLACE("SQL Tutorial", "SQL", "HTML");
Result
More Examples
Replace "X" with "M":
SELECT REPLACE("XYZ FGH XYZ", "X", "M");
Result
Replace "X" with "m":
SELECT REPLACE("XYZ FGH XYZ", "X", "m");
Result
Replace "x" with "m":
SELECT REPLACE("XYZ FGH XYZ", "x", "m");
Result
MySQL REVERSE() Function
Main Article :- MySql REVERSE() Function
The REVERSE() method returns a string that has been reversed.
Syntax
REVERSE(string)
Parameter Values
Parameter | Description |
---|---|
string | Required. The string to reverse |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
Reverse a string:
SELECT REVERSE("SQL Tutorial");
Result
Reverse the text in CustomerName:
SELECT REVERSE(CustomerName)
FROM Customers;
Result
sodaleh y sodaderapmE ollijurT anA
MySQL RIGHT() Function
Main Article :- MySql RIGHT() Function
The RIGHT() method takes a string and extracts a set of characters (starting from right).
Tip:Examine the LEFT() method as well.
Syntax
RIGHT(string, number_of_chars)
Parameter Values
Parameter | Description |
---|---|
string | Required. The string to extract from |
number_of_chars | Required. The maximum amount of characters that can be extracted. This method will return string if this parameter is more than the number of characters in string. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
Extract the following four characters from a string (beginning at the right):
SELECT RIGHT("SQL Tutorial is cool", 4) AS ExtractString;
Result
Extract the following 5 characters from the "CustomerName" column's content (beginning on the right):
SELECT RIGHT(CustomerName, 5) AS ExtractString
FROM Customers;
Result
lados
MySQL RPAD() Function
The RPAD() function right-pads a string with another string until it reaches a specified length.
Note: Examine the LPAD() method as well.
Syntax
RPAD(string, length, rpad_string)
Parameter Values
Parameter | Description |
---|---|
string | Required. This is the first string. This function eliminates the overfloating characters from the string if the length argument is more than the length parameter. |
length | Required. After it has been right-padded, the length of the string. |
rpad_string | Required. The string to right-pad to string |
Technical Details
Example
Pad the string to a total length of 20 by adding "ABC" to the right side.
SELECT RPAD("SQL Tutorial", 20, "ABC");
Result
Replace the string in "CustomerName" with "ABC" to make it 30 characters long:
SELECT RPAD(CustomerName, 30, "ABC") AS RightPadCustomerName
FROM Customers;
Result
Ana Trujillo Emparedados y hel
MySQL RTRIM() Function
The RTRIM() method eliminates spaces from the end of a string.
Syntax
RTRIM(string)
Parameter Values
Parameter | Description |
---|---|
string | Required. To eliminate trailing spaces from a string, use the following string. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
To remove spaces at the end of a string, use the following formula:
SELECT RTRIM("SQL Tutorial ") AS RightTrimmedString;
Result
MySQL SPACE() Function
The SPACE() method returns a string with the amount of space characters you choose.
Syntax
SPACE(number)
Parameter Values
Parameter | Description |
---|---|
number | Required. The maximum amount of space characters that should be returned |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
Return a string containing 10 spaces:
SELECT "A" + SPACE(10) + "B"
Result
MySQL STRCMP() Function
Two strings are compared using the STRCMP() function.
Syntax
STRCMP(string1, string2)
Parameter Values
Parameter | Description |
---|---|
string1, string2 | Required. The two strings to be compared |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
Compare the following two strings:
SELECT STRCMP("SQL Tutorial", "SQL Tutorial");
Result
Compare the following two strings:
SELECT STRCMP("SQL Tutorial", "HTML Tutorial");
Result
MySQL SUBSTR() Function
A substring is extracted from a string using the SUBSTR() method (starting at any position).
Note: The methods SUBSTR() and MID() are the same as SUBSTRING().
Syntax
SUBSTR(string, start, length)
Parameter Values
Parameter | Description |
---|---|
string | Required. The string to extract from |
start | Required. The starting point. It might be either good or negative. This method extracts from the beginning of the string if it is a positive integer. This method extracts from the end of the string if it is a negative integer. |
length | Optional. The maximum amount of characters that can be extracted. If this parameter is left blank, the entire string will be returned. (from the start position) |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
Remove a substring from a string (starting at position 5, remove three characters):
SELECT SUBSTR("SQL Tutorial", 5, 3) AS ExtractString;
Result
More Examples
Start at position 2 and extract 5 characters from the text in a column to create a substring:
SELECT SUBSTR(CustomerName, 2, 5) AS ExtractString
FROM Customers;
Result
na Tr
Extract a substring from a string (starting at position -5 and extracting 5 characters):
SELECT SUBSTR("SQL Tutorial", -5, 5) AS ExtractString;
Result
MySQL SUBSTRING() Function
Main Article :- MySql SUBSTRING() Function
A substring is extracted from a string using the SUBSTRING() method (starting at any position).
Note: The SUBSTR() and MID() functions are interchangeable with the SUBSTRING() function.
Syntax
SUBSTRING(string, start, length)
Parameter Values
Parameter | Description |
---|---|
string | Required. The string to extract from |
start | Required. The starting point. It might be either good or negative. This method extracts from the beginning of the string if it is a positive integer. This method extracts from the end of the string if it is a negative integer. |
length | Optional. The number of characters to extract. If omitted, the whole string will be returned (from the start position) |
Example
Remove a substring from a string (start at position 5 and remove 3 characters):
SELECT SUBSTRING("SQL Tutorial", 5, 3) AS ExtractString;
Result
More Examples
Start at position 2 and extract 5 characters from the text in a column to create a substring:
SELECT SUBSTRING(CustomerName, 2, 5) AS ExtractString
FROM Customers;
Result
na Tr
Remove a substring from a string (starting at point -5, remove 5 characters):
SELECT SUBSTRING("SQL Tutorial", -5, 5) AS ExtractString;
Result
MySQL SUBSTRING_INDEX() Function
The method SUBSTRING INDEX() returns a substring of a string before a given number of delimiters appear.
Syntax
SUBSTRING_INDEX(string, delimiter, number)
Parameter Values
Parameter | Description |
---|---|
string | Required. The original string |
delimiter | Required. The delimiter to search for |
number | Required. The number of times the delimiter must be searched. It might be either good or negative. If the value is positive, this method retrieves everything to the left of the delimiter. If the value is negative, this method returns everything to the right of the delimiter. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
Return a substring of a text that comes before a certain number of delimiters:
SELECT SUBSTRING_INDEX("www.simmanchith.com", ".", 1);
Result
Return a substring of a text that comes before a certain number of delimiters:
SELECT SUBSTRING_INDEX("www.simmanchith.com", ".", 2);
Result
MySQL TRIM() Function
Main Article :- MySql TRIM() Function
Leading and trailing spaces are removed from a string using the TRIM() method.
Syntax
TRIM(string)
Parameter Values
Parameter | Description |
---|---|
string | Required. To eliminate leading and trailing spaces from a string, use the following string. |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
To remove leading and trailing spaces from a string, follow these steps:
SELECT TRIM(' SQL Tutorial ') AS TrimmedString;
Result:
MySQL UCASE() Function
Main Article :- MySql UCASE() Function | MySql UPPER() Function
The UCASE() method changes the case of a string.
Note: The UPPER() function is equivalent to this one.
Syntax
UCASE(text)
Parameter Values
Parameter | Description |
---|---|
text | Required. The string to convert |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
Convert the text to all capital letters:
SELECT UCASE("SQL Tutorial is FUN!");
Result:
Convert the text in "CustomerName" to all capital letters:
SELECT UCASE(CustomerName) AS UppercaseCustomerName
FROM Customers;
Result:
ANA TRUJILLO EMPAREDADOS Y HELADOS
MySQL UPPER() Function
The UPPER() method raises the case of a string.
Note: The UCASE() method is the same as this one.
Syntax
UPPER(text)
Parameter Values
Parameter | Description |
---|---|
text | Required. The string to convert |
Technical Details
Works in: | From MySQL 4.0 |
---|
Example
Convert the text to all capital letters:
SELECT UPPER("SQL Tutorial is FUN!");
Result:
Make the following changes to the text in "CustomerName":
SELECT UPPER(CustomerName) AS UppercaseCustomerName
FROM Customers;
Result:
ANA TRUJILLO EMPAREDADOS Y HELADOS