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 data types will store the data length. For this SQL Server example, We are going to use the below-shown data

SQL DATALENGTH 1

SQL DATALENGTH Example 1

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 the DATALENGTH function.

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 Data Length directly
SELECT DATALENGTH ('SQL Server Tutorial') AS 'Data Length'
SELECT DATALENGTH ('SQL Server') AS 'Data Length'
SQL DATALENGTH 2

Below 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.

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

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

In the below statement, 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 SQL ALIAS Column.

SELECT DATALENGTH (@String_Exp) AS 'Data Length' 
SELECT DATALENGTH (@Str_Exp) AS 'Data Length' 

In the next line, We used the DATALENGTH Function directly on the string.

DATALENGTH Function Example 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.

USE [SQL Tutorial]
GO
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.