SQL Server DATALENGTH() Function

The DATALENGTH() function in SQL Server determines the size of an expression in bytes. This is particularly useful when working with strings and understanding how much storage space they consume, especially when dealing with different character sets.



DATALENGTH(): Definition and Usage

DATALENGTH() is a very practical function for managing text data. It provides the length of an expression in bytes, which is important to know when you are working with things like character encoding, storage space, or network transmissions. Unlike LEN(), DATALENGTH() includes both leading and trailing spaces in its calculation.

Syntax

Syntax

DATALENGTH(expression)
      

Parameter Values

Parameter Description
expression The expression whose length (in bytes) you want to determine. This can be a string literal, a column name, or any expression that results in a string value. If the expression is NULL, DATALENGTH() returns NULL. This is required.

Related Function

The LEN() function returns the length of a string in characters (not bytes). For strings using single-byte character sets, LEN() and DATALENGTH() will return the same value, but this is not true for multi-byte character sets.

Examples

Calculating the Byte Length of a String

This example shows getting the byte length of the string 'W3Schools.com'.

Syntax

SELECT DATALENGTH('W3Schools.com');
      
Output

13
      

Calculating the Byte Length Including Whitespace

This demonstrates that leading and trailing spaces are included in the byte count.

Syntax

SELECT DATALENGTH('   W3Schools.com   ');
      
Output

21
      

Calculating the Byte Length of a Different String

Another example showing the byte length of a different string.

Syntax

SELECT DATALENGTH('2017-08');
      
Output

7