Knowledge base / SQL

LENGTH in SQL: what MySQL, PostgreSQL and other engines count

I show how engines and input types change length measurements, and why the same filter may select different records after a report migration.

Kajo RudzińskiPublished Updated 5 min read

Two machines measure the same row of tiles using large and small units

LENGTH looks straightforward: supply text and receive a number. Difficulties arise when a query moves between databases or its input type changes. The same function name can measure a different unit.

Before using it, I establish the engine, input type and intended measurement. The synthetic examples below explain why. Expected results follow the documentation, without assuming that every SQL dialect provides one universal length function.

Start with the engine and unit

Engine and input Characters Bytes
MySQL 8.4, text CHAR_LENGTH LENGTH or OCTET_LENGTH
PostgreSQL 18, text or varchar LENGTH or CHAR_LENGTH OCTET_LENGTH
SQLite 3.43+, text LENGTH, before the first U+0000 OCTET_LENGTH
Oracle Database 19c, text LENGTH LENGTHB, subject to documented type restrictions
SQL Server 2022, text LEN, excluding trailing spaces DATALENGTH

This table follows the documentation for MySQL, PostgreSQL, SQLite, Oracle, and Microsoft’s LEN and DATALENGTH. It is a selection map rather than a promise of identical behaviour for every text type.

SQL Server does not provide a built-in LENGTH function with the meaning used in these examples. Oracle LENGTHB has restrictions including multibyte LOB input. I do not substitute a name blindly just because another engine returned an integer.

The SQLite examples assume version 3.43 or later. OCTET_LENGTH was added in SQLite 3.43.0; older installations may not provide it.

MySQL LENGTH counts bytes

For MySQL text, a multibyte character contributes several bytes. I explicitly choose utf8mb4 and use three Polish letters:

-- MySQL 8.4
SELECT
    LENGTH(_utf8mb4'ĄĆĘ') AS bytes_count,
    CHAR_LENGTH(_utf8mb4'ĄĆĘ') AS characters_count;
bytes_count characters_count
6 3

Each of these letters occupies two UTF-8 bytes. That does not establish that every Unicode character uses two bytes. For this particular representation, six bytes and three characters answer two different questions correctly.

If an import contract allows at most five characters, the text fits. If an export allows at most five UTF-8 bytes, it does not. Changing the unit changes acceptance even though the underlying text remains the same.

PostgreSQL LENGTH for text counts characters

For a PostgreSQL database using UTF8, the corresponding query shows the difference:

-- PostgreSQL 18; server_encoding = UTF8
SELECT
    LENGTH('ĄĆĘ') AS characters_count,
    OCTET_LENGTH('ĄĆĘ') AS bytes_count;
characters_count bytes_count
3 6

The claim that LENGTH counts bytes in both MySQL and PostgreSQL is therefore incorrect. The engine and type must be specified. The CHAR_LENGTH entry explains character counting further.

PostgreSQL also has a LENGTH variant for bytea, measuring bytes of binary data. The engine and function name alone therefore do not establish the unit without considering the argument type.

Trailing spaces and fixed-width types

For ordinary PostgreSQL text, LENGTH('A ') returns two. But character(n) introduces padding and conversion rules. Trailing spaces are removed when values are passed to many text functions. MySQL CHAR retrieval also differs from VARCHAR retrieval.

A declared column width is therefore not automatically the function’s result. A ten-character column can contain shorter meaningful content. I must decide whether I am examining the content, padding or byte representation.

SQL Server illustrates another difference using a typed Unicode literal:

-- SQL Server 2022
SELECT
    LEN(N'A ') AS characters_without_trailing_spaces,
    DATALENGTH(N'A ') AS bytes_count;

The results are 1 and 4: LEN excludes the trailing space, while DATALENGTH measures bytes of this two-character nvarchar literal. Four bytes do not mean four characters. Dividing every possible DATALENGTH result by two would not create a universal character counter either.

SQLite distinguishes text from BLOB input

SQLite LENGTH for text counts Unicode code points before the first U+0000. For a BLOB it counts bytes. NULL remains NULL. The documentation separates these cases explicitly.

-- SQLite 3.43+; text literal and BLOB literal
SELECT
    LENGTH('ABC') AS text_length,
    LENGTH(X'414200') AS blob_length;

Both results are 3, but the units and input interpretation differ. The second value contains three bytes, including a zero byte. It is not a missing NULL value. Identical output numbers can conceal a change of meaning after a type conversion.

Three trays show a row of tiles, an empty surface and a missing base panel

Check empty text and NULL separately

For text in MySQL, PostgreSQL and SQLite, an empty string has length zero and LENGTH(NULL) returns NULL. To find both kinds of missing content in an existing product table, I name them explicitly:

-- MySQL 8.4, PostgreSQL 18 or SQLite; textual product_name
SELECT product_id, product_name
FROM products
WHERE product_name IS NULL
   OR LENGTH(product_name) = 0;

For zero, the byte-versus-character distinction does not affect empty-value selection within this scope. It matters again for positive limits. Spaces alone are not empty text, so the filter does not select them. They require an additional cleaning or validation rule.

I do not extend this query to every engine in the comparison table. Oracle has its own empty-string rules, while SQL Server uses other function names. The dialect label is part of the example rather than a minor note beneath the code.

Measuring length does not truncate or validate future writes

A SELECT filter identifies records of interest. It neither shortens them nor protects subsequent inserts. A permanent rule needs an appropriate table constraint or input validation. The CHAR_LENGTH entry includes a constraint example.

Appending WHERE to INSERT with a VALUES clause is not the conditional validation pattern suggested by the old example. Before selecting the correct statement, I need to decide whether an invalid record should be rejected, corrected or sent for investigation.

Automatic truncation can turn two different product codes into the same code. Shortening a name may hide a distinction needed for matching. I first establish why the limit exists and what information can be discarded. A length function cannot answer those questions.

Exercise: predict a migration’s effect

Take three values: ASCII ABC, Polish ĄĆĘ and empty text. Predict LENGTH in MySQL with UTF-8 and LENGTH for PostgreSQL text. Among these values, only the Polish example produces different results for the two measurements.

Then determine which limit your report needs and name the output column to reveal its unit. Character length and byte length deserve separate names. When moving a query between engines, that decision can prevent apparently arbitrary data rejections.

Key takeaways

Does PostgreSQL LENGTH count bytes?

For text and varchar it counts characters. OCTET_LENGTH counts text bytes. The LENGTH variant for bytea measures bytes of binary input.

What should I use in SQL Server?

LEN counts characters excluding trailing spaces, while DATALENGTH counts bytes representing a value. Establish the required unit before choosing between them.

Does LENGTH(column) = 0 find NULL?

Not in the MySQL, PostgreSQL and SQLite examples here. LENGTH(NULL) returns NULL, so missing values require a separate IS NULL condition.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.