SQL Server LEN() Function: Count Characters in String

In SQL Server, the LEN() function returns the total count of the characters of the specified input string, excluding the trailing spaces.

LEN (string_expression)

Parameters

string_expression: A string value or a column of type char, varchar, or binary data type.

Return Value

Returns bigint if the input string is varchar(max), nvarchar(max) or varbinary data types. Else returns int.

Note: The LEN() function excludes trailing spaces. You can use the DATALENGTH() function if you want to include trailing spaces.

Example 1:

The following example returns the number of characters using the LEN() function.

Example: LEN()
SELECT LEN ('HELLO WORLD') AS Result

Example 2:

In the following example, the LEN() function is used on a string with trailing spaces. LEN ignores the trailing spaces as shown in the result.

Example: LEN()
SELECT LEN('HELLO WORLD   ') AS WithTrailingSpaces

Example 3:

In the following example, the LEN function is used with the column, FirstName of Employee table.

Example: LEN()
SELECT LEN(FirstName) AS LengthOfFirstName, FirstName FROM Employee;
Want to check how much you know SQL Server?