How to use the LENGTH() function in SQL
Overview
The LENGTH() function is used to return the number of characters in a string.
Syntax
The syntax for this function is as follows:
LENGTH(string)
Parameter
string: This represents the string whose length is to be returned.
Code example
The following code demonstrates how to use the LENGTH() function in SQL:
CREATE TABLE Person (ID int,first_name varchar(50),last_name varchar (50),gender varchar(10));-- Insert dataINSERT INTO PersonVALUES (1,'Sharon', 'Peller','Female');INSERT INTO PersonVALUES (2,'Paul', 'Dons','Male');INSERT INTO PersonVALUES (3,'Ameera', 'Abedayo','Female');INSERT INTO PersonVALUES (4,'Maria', 'Elijah','Female');INSERT INTO PersonVALUES (5,'David', 'Hassan','Male');INSERT INTO PersonVALUES (6,'Niniola', 'Disu','Female');INSERT INTO PersonVALUES (8,'Joe', 'Smith','Male');-- QuerySELECT LENGTH(first_name) AS no_of_char, genderFROM Person;
Code explanation
In the code above:
- Lines 1 to 7: We create a table called
Personwhich has the columnsid,name, andgender. - Lines 9 to 22: We add data into the
Persontable. - Lines 25 to 26: We use the
LENGTH()function to return the number of characters in thefirst_namecolumns to form a new column calledno_of_char.