SQL LEN Function

The SQL LEN function used to find the length of a specified expression. Or we can say, The SQL 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 LEN Function is

SELECT LEN (String_Expression)
FROM [Source]

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

String FUNCTION Table

SQL LEN Function Example

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 'SQLLength' 

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

Within this SQL 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 ‘Length’ using ALIAS.

SELECT LEN (@String_Expression) AS 'SQLLength' 

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

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

LEN Function Example 2

The SQL 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 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