LEN Function
The LEN function returns the number of characters in a string expression.
Syntax
LEN ( string_expression )
Parameters
| Parameter | Description | Data Type |
|---|---|---|
string_expression |
The expression that contains the characters that you want to count. string_expression can be a character string literal, or a column name, or a variable that contains a character string. |
char, varchar, nchar, nvarchar, text, ntext, varchar(max), nvarchar(max), text in row |
Return Type
int
Description
The LEN function counts the number of characters in the provided string. It does not count trailing spaces. If you need to include trailing spaces in the count, you can use the DATALENGTH function. The LEN function is equivalent to the LENGTH function in some other database systems.
Permissions
No special permissions are required to use the LEN function.
Examples
Example 1: Basic Usage
This example demonstrates how to use LEN to find the length of a simple string.
SELECT LEN('SQL Server');
Result:
10
Example 2: Using LEN with a Column
This example shows how to find the length of strings in a specific column of a table. Assume you have a table named Products with a column named ProductName.
SELECT ProductName, LEN(ProductName) AS ProductLength
FROM Products;
Example 3: Handling Trailing Spaces
Demonstrates how LEN ignores trailing spaces.
SELECT LEN('Microsoft '); -- Two trailing spaces
Result:
9
To count all characters, including trailing spaces, you would use DATALENGTH:
SELECT DATALENGTH('Microsoft '); -- Counts characters including spaces
Result:
11