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 data
INSERT INTO Person
VALUES (1,'Sharon', 'Peller','Female');
INSERT INTO Person
VALUES (2,'Paul', 'Dons','Male');
INSERT INTO Person
VALUES (3,'Ameera', 'Abedayo','Female');
INSERT INTO Person
VALUES (4,'Maria', 'Elijah','Female');
INSERT INTO Person
VALUES (5,'David', 'Hassan','Male');
INSERT INTO Person
VALUES (6,'Niniola', 'Disu','Female');
INSERT INTO Person
VALUES (8,'Joe', 'Smith','Male');
-- Query
SELECT LENGTH(first_name) AS no_of_char, gender
FROM Person;

Code explanation

In the code above:

  • Lines 1 to 7: We create a table called Person which has the columns id, name, and gender.
  • Lines 9 to 22: We add data into the Person table.
  • Lines 25 to 26: We use the LENGTH() function to return the number of characters in the first_name columns to form a new column called no_of_char.

Free Resources