The SQL LEN function helps find the length of a specified expression. Or we can say, The 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 or Length Function is
SELECT LEN (String_Expression) FROM [Source]
For this SQL Server Len function, we use the below data
SQL LEN Function Example
The String LEN function is used to count the number of characters inside a specified expression. For example, 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'
Within this Len function example, the 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 following line, we used the LEN String Function directly on the string.
--Finding Length directly SELECT LEN ('Learn SQL Server 2014') AS 'SQLLength'
LEN 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.
SELECT [FirstName] ,[LastName] ,[DepartmentName] ,LEN([DepartmentName]) AS [Dept Length] ,[Email] ,LEN([Email]) AS [Email Length] FROM [Employe]
SQL 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, 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