Sql Server Datalength Function

SQL Server: DATALENGTH Function

In this post explains how to use the DATALENGTH function in SQL Server (Transact-SQL) with syntax and examples.

Description

In SQL Server (Transact-SQL), the DATALENGTH function returns the length of an expression, in bytes.

Syntax

The syntax for the DATALENGTH function in SQL Server (Transact-SQL) is:

DATALENGTH( expression )

Parameters or Arguments

expression

The data type that you wish to return the length for.

Note

  • The DATALENGTH function counts both trailing spaces and preceeding spaces when calculating the length of the expression.
  • The DATALENGTH function will return NULL, if the expression is NULL.
  • See also the LEN function which does not include trailing spaces in the length calculation.

Applies To

The DATALENGTH function can be used in the following versions of SQL Server (Transact-SQL):

  • SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005

Example

Let's look at some SQL Server DATALENGTH function examples and explore how to use the DATALENGTH function in SQL Server (Transact-SQL).

For example:

SELECT DATALENGTH('AODBA.com');
Output: 16

SELECT DATALENGTH('   AODBA.com   ');
Output: 22

SELECT DATALENGTH(1234);
Output: 4

SELECT DATALENGTH('2004-05-01');
Output: 10

SELECT DATALENGTH(' ');
Output: 1

SELECT DATALENGTH('');
Output: 0

SELECT DATALENGTH(NULL);
Output: NULL