Tag Archives: Length of a string

How to get the Length of a String in Sql Server?

In Sql Server we can use the LEN() function to get the length of a string. This function returns the number of characters in a string except the trailing spaces, but it includes the leading spaces.

[ALSO READ] Difference between Len() and Datalength() functions in Sql Server

Syntax
LEN(string)

Return Type
This function returns an INT representing the number of characters in a string. In case the input string is VARCHAR(MAX), NVARCHAR(MAX) or VARBINARY(MAX), it returns BIGINT.

Let us understand this function with examples:

Example 1: Get the Length of a string

SELECT LEN('Basav')

RESULT:
5

Example 2: Trailing space at the end of a string are ignored.

SELECT LEN('Basav ')

RESULT:
5

Example 3: Leading space at the beginning of a string are counted.

SELECT LEN(' Basav')

RESULT:
6

Example 4: Spaces in the middle of a string are counted.

SELECT LEN('A & B')

RESULT:
5

Example 5: Length of NULL.

SELECT LEN(NULL)

RESULT:
NULL