SQL DATALENGTH

The SQL DATALENGTH is used to return the number of bytes used to represent a specified expression. The syntax of DATALENGTH in SQL Server is

SELECT DATALENGTH (String_Expression)
FROM [Source]

This Sql Server DATALENGTH function is useful for VARCHAR, NVARCHAR, VARBINARY, TEXT, NTEXT, and IMAGE Data Types because these datatypes will store the data length. For this example, We are going to use the below-shown table

Employee Table Records 1

SQL DATALENGTH Example

The DATALENGTH Function is used to return the number of bytes used to represent a given expression. The following query will show multiple ways to use it.

The first four lines of SQL Server code are used to declare the string variable of Data Type Varchar and Nvarchar, and assigning the same data to both the variables.

In the below two statements, We used the DATALENGTH function to find the data length of both the variables. We also assigned a new name to that result as ‘Data Length’ using the ALIAS Column.

In the next line, We used it directly on the string.

DECLARE @String_Exp VARCHAR(50)
SET @String_Exp = 'Learn SQL Server' 

DECLARE @Str_Exp NVARCHAR(50)
SET @Str_Exp = 'Learn SQL Server' 
 
SELECT DATALENGTH(@String_Exp) AS 'Data Length' 
SELECT DATALENGTH(@Str_Exp) AS 'Data Length'
 
--Finding directly
SELECT DATALENGTH('SQL Server Tutorial') AS 'Data Length'
SELECT DATALENGTH('SQL Server') AS 'Data Length'
SQL DATALENGTH 2

The SQL Server DATALENGTH function also allows you to find the number of bytes in a column. In this example, We are going to find the Data length of a Department Name and Email columns.

SELECT [FirstName]
      ,[LastName]
      ,[DepartmentName]
      ,DATALENGTH([DepartmentName]) AS [Dept Data Length]
      ,[Email]
      ,DATALENGTH([Email]) AS [Email Data Length]
 FROM [Employe]
SQL DATALENGTH 3

Comments are closed.