LENGTH function in SQL

In SQL, the LENGTH function (or LEN in some databases like SQL Server) is used to return the length of a string. This length is typically measured in characters.

Syntax The syntax for the LENGTH function can vary slightly between different SQL databases:

MySQL and PostgreSQL

SELECT LENGTH(string_column) FROM table_name;

SQL Server

SELECT LEN(string_column) FROM table_name;

Example: Create the Employees table.

SQL

CREATE TABLE Employees (
   EmployeeID INT,
    Name VARCHAR(20),
    Age int,
    Salary VARCHAR(10),
    Department VARCHAR(25),
    Gender VARCHAR(1)
);      

Insert the data in the Employees table.

SQL

INSERT INTO Employees VALUES
(1, 'Ashish', 24, '25000', 'Electrical', 'M'), 
(2, 'Kirshan', 32, '30000', 'Electrical', 'M'),
(3, 'Anjali', 20, '25000', 'Electronics', 'F'),
(4, 'Manjulika', 30, '15000', 'Electrical', 'F'),
(5, 'Katrina', 37, '18000', 'Computer', 'F'),
(6, 'Esha', 37, '20000', 'Computer', 'F'),
(7, 'Ankita', 20, '9000', 'Electronics', 'M'), 
(8, 'Meenakshi', 30, '15000', 'Computer', 'F'),
(10, 'Alia', 37, '16000', 'Electronics', 'F');       

By using the Create table and insert statement we reach to the following table in our database:

SQL

Select * from Employees;

Table: Employees

EmployeeIDNameAgeSalaryDepartmentGender
1Ashish2425000ElectricalM
2Kirshan3230000ElectricalM
3Anjali2025000ElectronicsF
4Manjulika3015000ElectricalF
5Katrina3718000ComputerF
6Esha3720000ComputerF
7Ankita209000ElectronicsM
8Meenakshi3015000ComputerF
10Alia3716000ElectronicsF

Query to get the length of each Name

MySQL and PostgreSQL

SELECT EmployeeID, Name, LENGTH(Name) FROM employees;

SQL Server

SELECT EmployeeID, Name, LEN(Name) FROM employees;

The result of the above query is shown below:

EmployeeIDNameLENGTH(Name)
1Ashish6
2Kirshan7
3Anjali6
4Manjulika9
5Katrina7
6Esha4
7Ankita6
8Meenakshi9
10Alia4