How is the len function used in SQL?
The LEN function in SQL is used to return the length of a string. It takes a string as a parameter and returns the number of characters in that string. It can be used to calculate the length of a string.
For example, regarding the table and data below:
CREATE TABLE students (
id INT,
name VARCHAR(50)
);
INSERT INTO students (id, name)
VALUES (1, 'John Doe'),
(2, 'Jane Smith'),
(3, 'Bob Johnson');
You can use the LEN function to get the length of each student’s name.
SELECT name, LEN(name) AS name_length
FROM students;
The result will be:
name | name_length
-------------------------
John Doe | 8
Jane Smith | 10
Bob Johnson | 11
In this example, the LEN function is used to calculate the number of characters in each student’s name and returns it as a column called name_length.