LEN Function
- DECLARE @Name VARCHAR(20)='rakesh'
- SELECT LEN(@Name) as [len]
- DECLARE @Name VARCHAR(20)='rakesh '
- SELECT LEN(@Name) as [len]
The LEN function returns the number of characters in a variable. It also removes the trailing spaces and then return the length.
Example 1

Example 2

When we observe above variable assigned 'rakesh ' string after that added 3 spaces. The LEN function removes trailing spaces not leading spaces.
- DECLARE @Name VARCHAR(20)='rakesh'
- SELECT DATALENGTH(@Name) as [DataLength]
- DECLARE @Name VARCHAR(20)=' rakesh '
- SELECT DATALENGTH(@Name) as [DataLength]
- DECLARE @Name NVARCHAR(20)=' rakesh '
- SELECT DATALENGTH(@Name) as [DataLength]
DATALENG function returns the number of bytes occupy in a variable. It also considered the spaces also.
Example 1

Example 2

In above example before 'r' and after 'h' we added space that why data length should be 8.
Example 3

In varchar each character is allows 1 byte. It does not support Unicode characters.
In nvarchar each character is allows2 byte. It support's Unicode characters.

Rajan MishraPosted Dec 5, 2019, 5:32 AM
Good but many scenarios are left.
SubashPosted Oct 23, 2016, 9:48 PM
Thanks for share
Nishant KumarPosted Nov 6, 2014, 12:17 PM
Nice.DataLength first example output should be 6