// strings reference

SQL DATALENGTH function

SQL Server's byte-level length: the number storage and truncation math needs, where LEN reports characters and skips trailing spaces.

Categoria
Strings
Returns
integer
In this category
45 of 172

Sintaxe

DATALENGTH(expression)

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim Supported under this name.
PostgreSQL Not built in No built-in equivalent.
MySQL Not built in No built-in equivalent.
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

Exemplos

SQL Server

SELECT LEN(N'ab ') AS chars, DATALENGTH(N'ab ') AS bytes;
-- 2, 6

SQL Server

SELECT DATALENGTH(big_note) AS stored_bytes FROM docs
ORDER BY stored_bytes DESC;

Bom saber

  • nvarchar data counts 2 bytes per character (UTF-16): DATALENGTH(N'ab') is 4, LEN(N'ab') is 2. Since 2019, UTF-8 collations on varchar change that ratio too.
  • Trailing spaces count: DATALENGTH('ab ') is 3 while LEN('ab ') is 2. Leading spaces count for both.
  • On varchar(max) and varbinary(max) it reports the actual data size, not the declared maximum, useful for finding oversized rows.
  • LEN on nvarchar counts UTF-16 code units under most collations, so an emoji is 2. Supplementary-character collations (_SC, or the _140 family) count it as 1. DATALENGTH is 4 bytes either way.

Questions about DATALENGTH

Why do LEN and DATALENGTH disagree?

LEN counts characters and ignores trailing spaces; DATALENGTH counts stored bytes including trailing spaces, and nvarchar bytes are 2 per character. They answer different questions.

Does DATALENGTH work on non-string types?

Yes. It returns the storage size of any expression: 4 for int, 8 for datetime, the actual bytes for blobs. It is the closest thing to sizeof in T-SQL.

What is the cross-engine equivalent?

OCTET_LENGTH on PostgreSQL and MySQL, LENGTHB on Oracle. All three report bytes; only DATALENGTH adds the trailing-space and UTF-16 specifics.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.