Save Big on Cyber Monday! Up to 40% Off
ends in   {{days}}
Days
{{timeFormat.hours}}
:
{{timeFormat.minutes}}
:
{{timeFormat.seconds}}

SQL Server DATALENGTH() Function: Syntax, Examples, and Use Cases

SQL Server DATALENGTH exposes what most functions ignore: the true storage cost of your data. It's your frontline defense against silent truncation and structural breakpoints, especially in systems handling binary files, multibyte text, and strict column constraints. But to use it with precision, you first need to understand how it behaves across data types.

In this guide, you'll learn how DATALENGTH works across different data types, especially when using a professional SQL Server IDE. dbForge Studio for SQL Server helps DBAs, analysts, and data architects work faster. You can write and optimize SQL code, design databases visually, compare and sync schemas and data, generate scripts, and simplify administration. This high-end IDE makes working with SQL Server easier and more efficient.

What is the DATALENGTH() function in SQL Server?

DATALENGTH() is a built-in SQL Server function that returns the number of bytes used to store an expression. It is the definitive way to measure the actual storage footprint of a value, critical when working with variable-length data, binary content, or size-constrained columns.

This differs from LEN(), which reports the number of characters in a string. For example, while LEN(N'abc') returns 3, DATALENGTH(N'abc') returns 6, since each NVARCHAR character consumes 2 bytes. This distinction has direct implications when working with Unicode, multibyte characters, or when storage limits are a concern.

Beyond strings, DATALENGTH() works across various SQL Server data types, including:

  • Text: CHAR, VARCHAR, NCHAR, NVARCHAR
  • Binary: BINARY, VARBINARY, IMAGE
  • Deprecated LOB types: TEXT, NTEXT

Real-world applications include:

  • Storage analysis: Understand and optimize how much space your data occupies.
  • Data integrity: Detect potential truncation issues before they cause errors.
  • Binary data handling: Accurately measure the size of stored files, images, or blobs.

But to use DATALENGTH() effectively, you need to understand its syntax, input rules, and what it returns under different conditions.

SQL Server DATALENGTH() syntax

The DATALENGTH() function in SQL Server takes a single argument as shown below.

DATALENGTH(expression)

The expression can be any valid SQL Server value, whether a column, variable, literal, or return value from another function. However, it must be of a supported data type, such as VARCHAR, NVARCHAR, VARBINARY, IMAGE, or a similar type.

The output is an int representing the number of bytes used to store that expression.

Example

SELECT DATALENGTH('abc');       -- Returns 3 
SELECT DATALENGTH(N'abc');      -- Returns 6 (NVARCHAR = 2 bytes/char) 
SELECT DATALENGTH(NULL);        -- Returns NULL 
Note
If the input is NULL, the function returns NULL, not zero.

Understanding this structure ensures precise control when validating storage limits, writing conditional logic, or accurately measuring binary and multibyte values.

Key differences between DATALENGTH() and LEN() in SQL Server

Although LEN() and DATALENGTH() in SQL Server are often used together, they serve fundamentally different purposes. The table below compares them.

Function Measures Includes trailing spaces? Returns NULL for NULLs?
LEN() Characters No No (returns 0)
DATALENGTH() Bytes Yes Yes

Practical implications

  • Character vs. byte count: LEN() returns character count; DATALENGTH() returns byte size. Use the latter when storage constraints or multibyte data types are involved.
  • Trailing spaces: DATALENGTH() includes them; LEN() does not. This is particularly important for fixed-length fields, padding, or byte-accurate audits.
  • NULL behavior: LEN(NULL) yields 0; DATALENGTH(NULL) yields NULL. The latter correctly distinguishes missing data from empty values.
Note
Selecting the incorrect function in size validation, filtering, or auditing can yield misleading results, particularly with multibyte characters or padded fields.

To see how these differences play out in practice, let’s look at specific use cases and data types.

Examples of using DATALENGTH() in SQL Server

The following examples illustrate how the SQL Server DATALENGTH() function behaves across various data types and scenarios.

Example 1: VARCHAR vs. NVARCHAR

SELECT DATALENGTH('abc');       -- Returns 3 
SELECT DATALENGTH(N'abc');      -- Returns 6

In this case, 'abc' is a VARCHAR value, stored as one byte per character. N'abc' is NVARCHAR, which uses two bytes per character due to Unicode encoding. DATALENGTH() accurately reflects this storage difference.

Example 2: Trailing spaces

SELECT DATALENGTH('abc ');      -- Returns 4 
SELECT LEN('abc ');             -- Returns 3

Trailing spaces are included in the byte count for DATALENGTH(), but excluded by LEN(). This is particularly important when validating input, auditing storage, or comparing values in fixed-length fields.

Example 3: NULL values

SELECT DATALENGTH(NULL);        -- Returns NULL 
SELECT LEN(NULL);               -- Returns NULL

DATALENGTH() returns NULL, preserving the true state of the data.

Example 4: Binary data

DECLARE @bin VARBINARY(10) = 0x4D5A; 
SELECT DATALENGTH(@bin);        -- Returns 2

For binary types like VARBINARY, DATALENGTH() reports the exact number of bytes stored. This is essential when working with images, documents, or file blobs stored in the database. It ensures stored content remains within size limits and facilitates monitoring data growth.

Beyond isolated examples, the DATALENGTH() SQL Server function proves especially valuable in several recurring real-world scenarios.

Common use cases for DATALENGTH()

Below are three high-impact use cases where DATALENGTH() plays a critical role.

Checking if a column is non-empty

To identify rows where data is physically stored, even if it's just whitespace, DATALENGTH() provides a reliable check. This is especially useful in data audits or when distinguishing between empty and null values, where LEN() may fall short.

SELECT * FROM table WHERE DATALENGTH(column) > 0;

Preventing data truncation

Before inserting data into fixed-length or size-constrained columns, use DATALENGTH() to verify that the byte size of the input won't exceed the defined limit. This prevents silent truncation, which is a common issue when working with Unicode or binary inputs.

IF DATALENGTH(@value) <= 50   
    INSERT INTO TargetTable(Column) VALUES (@value);

Measuring the size of a file or binary content

In applications that store binary data, such as PDFs, images, or blobs, DATALENGTH() accurately measures the storage size in bytes. This is essential for enforcing file size limits, optimizing storage, and validating input during the upload process.

SELECT DATALENGTH(FileContent) FROM Documents WHERE Id = 101;

However, to use DATALENGTH() with confidence, it's essential to understand how it behaves across different data types.

Byte size by data type: What DATALENGTH() measures

DATALENGTH() reports the actual storage size in bytes, and its behavior varies depending on the data type. This distinction is critical when designing schemas, enforcing storage constraints, or handling multibyte input.

Data type Bytes per character/item
CHAR, VARCHAR 1 byte
NCHAR, NVARCHAR 2 bytes (Unicode encoding)
VARBINARY The exact size of stored content

For character data, the function reflects encoding cost: NVARCHAR requires twice the space of VARCHAR for the same string. For binary types like VARBINARY, the result corresponds to the exact number of bytes stored, regardless of the declared length.

Special case: Legacy LOB types

TEXT and NTEXT, now deprecated, are still measured accurately by the DATALENGTH() function. However, their use is discouraged in modern SQL Server environments. Replace them with VARCHAR(MAX) or NVARCHAR(MAX) for better compatibility and future-proofing.

Conclusion

In SQL Server environments, knowing how data is stored is just as important as knowing what it contains. This helps you ensure that what’s stored fits within defined constraints, won’t break during migrations, and can be trusted when storage limits are low or multibyte encoding is in play.

However, to work efficiently at this level of precision, a dedicated SQL Server IDE—dbForge Studio for SQL Server—can facilitate faster, more transparent, and easier integration into real-world workflows.

Download dbForge Studio for SQL Server to run and optimize DATALENGTH queries with complete byte-level visibility.

FAQ

Can DATALENGTH be used in computed columns?

Yes. DATALENGTH() can be used in computed columns in SQL Server, provided the expression is deterministic. If it always returns the same value for the same input and doesn't reference volatile functions (like GETDATE()), SQL Server allows it in persisted computed columns.

Does DATALENGTH return 0 for NULL?

No. DATALENGTH(NULL) returns NULL, not zero.

What's the return type of DATALENGTH()?

DATALENGTH() returns an int that represents the number of bytes used to store the input expression. If the input is NULL, the return value is also NULL.