MySQL Length Function

MySQL Length function is one of the String methods, which is useful to find the length of the user-specified expression (or column value). Or we can simply say the MySQL String Length Function counts the number of characters inside an expression and returns the results, and the basic syntax of it is as shown below:

SELECT LENGTH (String_Expression)
FROM Source

For this MySQL String Length Function demonstration, we are going to use the below-shown data

Employee Table Rows 1

MySQL String Length function Example

The string length function counts the number of characters inside a specified expression. The following query shows multiple ways to use this.

SELECT 
	LENGTH ('Learn MySQL Server') AS `SQLLength`,
        LENGTH ('Tutorial Gateway') AS `Website Length`;

Remember, it counts the empty space as well.

MySQL String Length Example 2

This method also allows you to find the data length inside the columns. In this MySQL function example, we will find the length of two string columns Department Name and Email column.

SELECT  FirstName, LastName, 
	DepartmentName, 
        LENGTH(DepartmentName) AS 'Department Length',
        Email,
        LENGTH(Email) AS 'Email Length'
FROM employe;
MySQL String Length Example 3

MySQL Length Function WHERE Condition

In this String method example, we show you, How to use this at the where clause condition. First, we are finding the length of the Department Name and the Email columns. Next, we used it in the where clause to check whether the email characters are greater than 15 or not.

SELECT  FirstName, LastName, 
	DepartmentName, 
        LENGTH(DepartmentName) AS 'Department Length',
        Email,
        LENGTH(Email) AS 'Email Length'
FROM employe
WHERE LENGTH(Email) > 15;

Instead of using this method in the where clause, you might be tempted to use the Alias name in the where clause. But, MySQL WHERE Clause does not understand the ALIAS Column name declared in the SELECT Statement.

Where Example 4

MySQL String Length Where order By Clause Example

In this MySQL example, we write the string length function in the Command prompt. Here, we are using this function along with the Where clause and Order By Clause. First, Where will restrict the records whose department name character count is greater than five? Next, Order by sorting the records in rever order based on their characters.

SELECT  FirstName, LastName, 
	DepartmentName, 
        LENGTH(DepartmentName) AS `Department Length`,
        Email,
        LENGTH(Email) AS `Email Length`
FROM employe
WHERE LENGTH(DepartmentName) > 5
ORDER BY `Department Length` DESC;
Command prompt Example 5