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 Length Example

The MySQL 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 count the empty space as well.

MySQL Length Example 2

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

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

MySQL 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.

MySQL Length Example 4

String Length Command prompt Example

In this example, we write the MySQL string length function in Command prompt. Here, we are using this function along with 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;
MySQL Length Example 5