How to Get the Length of a String in MySQL

Contents
In this article, you will learn how to get the length of a string in MySQL.
Getting the length of a string in MySQL
In MySQL, you can use the LENGTH() function to get the length of a string. The LENGTH() function returns the number of characters in a string, including spaces.
Syntax
LENGTH(str);
Examples
Here are some examples of using the LENGTH() function in MySQL:
Getting the length of a string
To get the length of a string, you can use the LENGTH() function.
Syntax
SELECT LENGTH(str);
Example
SELECT LENGTH('Hello World');
Output:
+----------------+
| LENGTH('Hello World') |
+----------------+
| 11 |
+----------------+
In this example, the LENGTH() function returns the length of the string ‘Hello World’, which is 11.
Getting the length of a column value
You can also use the LENGTH() function to get the length of a column value.
Syntax
SELECT LENGTH(column_name) FROM table_name;
Example
SELECT LENGTH(name) FROM employees;
Output:
+--------------+
| LENGTH(name) |
+--------------+
| 7 |
| 5 |
| 9 |
| 10 |
+--------------+
In this example, the LENGTH() function returns the length of the name column in the employees table.
Using the length of a string in a WHERE clause
You can use the LENGTH() function in a WHERE clause to filter records based on the length of a string.
Syntax
SELECT * FROM table_name WHERE LENGTH(column_name) = length_value;
Example
SELECT * FROM employees WHERE LENGTH(name) = 7;
Output:
+----+----------+--------+--------+
| id | name | salary | hire_date |
+----+----------+--------+--------+
| 1 | John | 50000 | 2020-01-01 |
| 3 | Michael | 60000 | 2020-02-01 |
+----+----------+--------+--------+
In this example, the SELECT statement returns all the records from the employees table where the length of the name column is equal to 7.