SQL LEN Function

The SQL LEN function used to find the length of a specified expression. Or we can say, The SQL server LEN Function will count the number of characters inside the given expression and returns the INT results.

SQL LEN Function Syntax

The syntax of the SQL Server LEN Function is

SELECT LEN (String_Expression)
FROM [Source]

For this SQL Server Length function, we use the below data

SQL LEN FUNCTION

SQL LEN Function Example 1

The String LEN function is used to count the number of characters inside a specified expression. This query uses the String LEN function to find the length of a string expression.

DECLARE @String_Expression varchar(50)
SET @String_Expression = 'Learn SQL Server' 

SELECT LEN (@String_Expression) AS 'SQL Length' 

--Finding Length directly
SELECT LEN ('Learn SQL Server 2014') AS 'SQL Length'
SQL LEN FUNCTION 1

Within this Len function example query, declared a string variable and set the string data.

DECLARE @String_Expression varchar(50)
SET @String_Expression = 'Learn SQL Server'

We used this LEN function to find the length of a string variable @String_Expression and assigned a new name ‘SQL Length’ using SQL ALIAS.

SELECT LEN (@String_Expression) AS 'SQL Length' 

In the next line, we used the LEN String Function directly on the string.

--Finding Length directly
SELECT LEN ('Learn SQL Server 2014') AS 'SQL Length'

LEN Function Example 2

The LEN function also allows you to find the length of expressions inside the columns. In this SQL Server example, We will find the length of a [Department Name] and the Email length as well.

SELECT [FirstName]
      ,[LastName]
      ,[DepartmentName]
      ,LEN([DepartmentName]) AS [Dept Length]
      ,[Email]
      ,LEN([Email]) AS [Email Length]
 FROM [Employe]
SQL LEN FUNCTION 2

LEN Function in WHERE Condition

In this example, we use the string LEN function inside the Where Clause. For instance, The following string len query will check whether the length of a [Department Name] is greater than 10 or not. If the given condition is TRUE, then the SQL SELECT Statement will display the records.

SELECT [FirstName]
      ,[LastName]
      ,[DepartmentName]
      ,LEN([DepartmentName]) AS [Dept Length]
      ,[Email]
      ,LEN([Email]) AS [Email Length]
 FROM [Employe]
 WHERE LEN([DepartmentName]) > 10
SQL LEN FUNCTION 3