DATALENGTH

DATALENGTH is a SQL Server function that returns the total number of bytes used to represent a column data. It's primarily used to determine the byte length of a given value or expression.

DATALENGTH( expression )

  • expression: This refers to an expression of any type except for text, ntext, image, cursor, and timestamp. DATALENGTH() function is used to measure the length (in bytes) of the expression.

Example

DECLARE @message nvarchar(50);
SET @message = 'Hello, SQL Server!';
SELECT DATALENGTH(@message) as length;

Output

length
-----------
28

Explanation

The DATALENGTH() function returns the number of bytes used to represent an expression’s value. Here, the string ‘Hello, SQL Server!’ returns 28. As we use nvarchar, each character is two bytes, so the length is double of the number of characters.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.