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

1 thought on “How to get the Length of a String in Sql Server?

  1. Awesome
    Awesome
    Awesome
    Teaching is an art and need dedication and focus

    Thanks for educating the community and
    Appreciate your volunteership

    Keep posting to resolve or solve simple to critical and hard problems on SQL

    I have seen your posts, I like it and love it

Leave a Reply

Your email address will not be published. Required fields are marked *