length
Use the length() function to find the length of a string (for example, the number of characters in a given string). It accepts a string as a parameter. The syntax of the length function is:
LENGTH(string)
The input type is a string, and the return type is int, as it returns the number of characters.
Special cases:
-
If a NULL value is passed in the function. (For example,
LENGTH(NULL), it returnsNULL). -
If the parameter is an empty string
LENGTH(''), it returns 0. -
If the parameter is a space character
LENGTH(' '), not empty or NULL, it returns 1 as it is not empty anymore.
Examples
Basic length() function
This example uses the length() function to find out the length of a string text:
SELECT LENGTH ('Redpanda SQL Tutorial');
The query returns:
+------------+
| length |
+------------+
| 21 |
+------------+
length() function using columns
The following example uses the length() function on a personal_details table containing id, first_name, last_name, and gender columns for retail store employees.
CREATE TABLE personal_details (
id int,
first_name text,
last_name text,
gender text
);
INSERT INTO personal_details
(id, first_name, last_name, gender)
VALUES
(1,'Mark','Wheeler','M'),
(2,'Tom','Hanks','M'),
(3,'Jane','Hopper','F'),
(4,'Emily','Byers','F'),
(5,'Lucas','Sinclair','M');
SELECT * FROM personal_details;
The query shows this table:
+-----+-------------+-------------+----------+
| id | first_name | last_name | gender |
+-----+-------------+-------------+----------+
| 1 | Mark | Wheeler | M |
| 2 | Tom | Hanks | M |
| 3 | Jane | Hopper | F |
| 4 | Emily | Byers | F |
| 5 | Lucas | Sinclair | M |
+-----+-------------+-------------+----------+
The query returns the last name and the length of the last name from the personal_details table, where the length of the last_name is greater than 5.
SELECT last_name,length(last_name)
AS "Length of Last Name"
FROM personal_details
WHERE LENGTH(last_name) > 5;
The output displays all those items in the last_name column with a length of more than 5 characters:
+---------------+-----------------------+
| last_name | Length of Last Name |
+---------------+-----------------------+
| Wheeler | 7 |
| Hopper | 6 |
| Sinclair | 8 |
+---------------+-----------------------+