Monday, 20 April 2015

Interview Question - What is the difference between LEN() and DATALENGTH() function ?

This question was faced by friend in a project allocation interview.

From the look of it both the function appears to be same but they are not. One gives the total number  (count) of characters in the string while second gives the number of bytes occupied by the characters in the string. 

As a SQL developer while dealing with string, quite often we end up using LEN() function. But DATALENGTH() isn't used that often.

The LEN() function is a String function while DATLENGTH() comes under data type function.

To understand the output of DATALENGTH() function one must know how much bytes are occupied for the different datatypes. 

As you can see the screenshot below 
LEN() function for INT variable with value 8 returns 1 while DATALEGTH() returns 4. This is because INT datatype takes up 4 bytes in the memory.

Similarly for CHAR data type is accounted for 1 byte hence both the function are returning 1 as a output. While NCHAR() occupies 2 bytes/character hence LEN() returns 1 while DATALENGTH() returns 2 for single character.

@Str CHAR(1'c',
@Str1 NCHAR(1'c'
SELECT LEN(@IAS Len_Function,DATALENGTH(@IAS DataLength_Function

SELECT LEN(@StrAS Len_Function,DATALENGTH(@StrAS DataLength_Function  

SELECT LEN(@Str1AS Len_Function,DATALENGTH(@Str1AS DataLength_Function  

For more details on the function please refer following links

No comments:

Post a Comment