Knowledge base / SQL

CHAR_LENGTH in SQL: characters, bytes and text validation

I show how to measure text length, distinguish it from byte counts and avoid confusing a length limit with complete validation.

Kajo RudzińskiPublished Updated 4 min read

A measuring device examines large tiles above a separate row of smaller units

I want to find overlong codes, inspect an empty name or prepare a field for export. CHAR_LENGTH helps with these tasks. Before comparing its result with a limit, however, I establish the unit: characters, bytes or elements perceived by a reader.

This entry focuses on text in MySQL 8.4 and PostgreSQL 18. The examples are synthetic and their expected results follow the documentation. I check both the name and meaning of a function before moving it between engines.

Basic syntax and a small example

CHAR_LENGTH takes a text value and returns its character count. CHARACTER_LENGTH is an equivalent name in both engines, as documented by MySQL and PostgreSQL.

-- MySQL 8.4 or PostgreSQL 18; text literals
SELECT
    CHAR_LENGTH('ABC') AS plain_length,
    CHAR_LENGTH('A B') AS spaced_length,
    CHAR_LENGTH('') AS empty_length,
    CHAR_LENGTH(NULL) AS missing_length;
plain_length spaced_length empty_length missing_length
3 3 0 NULL

The space between letters counts as a character. Empty text has length zero, while missing data remains NULL. I do not automatically merge these cases because they can indicate different import problems.

Trailing spaces also matter for these measurements of text or varchar values. Fixed-width CHAR columns introduce engine-specific padding and conversion rules. I therefore inspect the column definition before extending a simple literal example to every input type.

Łódź has four characters and seven UTF-8 bytes

The Polish city name Łódź contains four characters: Ł, ó, d and ź. In the shown UTF-8 representation, Ł, ó and ź use two bytes each, while d uses one. The total is seven bytes. It is neither five characters nor seven letters.

In MySQL, I explicitly choose the literal’s character set:

-- MySQL 8.4
SELECT
    CHAR_LENGTH(_utf8mb4'Łódź') AS characters_count,
    LENGTH(_utf8mb4'Łódź') AS bytes_count;
characters_count bytes_count
4 7

For a PostgreSQL database using UTF8 encoding, the corresponding query differs:

-- PostgreSQL 18; server_encoding = UTF8
SELECT
    CHAR_LENGTH('Łódź') AS characters_count,
    LENGTH('Łódź') AS length_result,
    OCTET_LENGTH('Łódź') AS bytes_count;
characters_count length_result bytes_count
4 4 7

This is an important dialect difference. PostgreSQL LENGTH for text counts characters; MySQL LENGTH counts bytes. The separate LENGTH entry develops that distinction.

Filter by length and handle NULL separately

Suppose an existing products table contains a textual product_code. Its import contract requires between three and twelve characters. I can find violations with the following condition:

-- MySQL 8.4 or PostgreSQL 18; existing products table
SELECT product_code, CHAR_LENGTH(product_code) AS code_length
FROM products
WHERE product_code IS NULL
   OR CHAR_LENGTH(product_code) < 3
   OR CHAR_LENGTH(product_code) > 12;

I check NULL separately. Comparing its length with a number does not evaluate to true and select the missing value. Empty text is selected by the lower bound, while a code containing exactly twelve characters remains acceptable.

This filter checks length alone. Three spaces have three characters and satisfy the range. If leading or trailing spaces are forbidden, I need another rule. A restricted alphabet or a requirement to reference a product catalogue also needs a separate check.

A width gauge separates short rows of cards from a row extending beyond its guide

A table constraint has its own limits

A new PostgreSQL table can express the length rule as a constraint. The following definition illustrates that requirement for use in an appropriate environment:

-- PostgreSQL 18
CREATE TABLE product_codes (
    product_code text NOT NULL,
    CONSTRAINT product_code_length
        CHECK (CHAR_LENGTH(product_code) BETWEEN 3 AND 12)
);

The constraint documentation explains why CHECK does not replace NOT NULL. An unknown CHECK result does not reject a row, so I state the mandatory-field requirement separately. The lower bound rejects empty text but still accepts three spaces.

Adding a constraint to an existing table changes its accepted data and requires examining current records. This entry explains the rule rather than supplying a command to paste blindly into a production database. The allowed values need to be established first.

A visible letter may contain several code points

A character displayed on screen does not always correspond to one Unicode code point. The letter é can be represented by U+00E9 or by e followed by the combining acute accent U+0301. The Unicode FAQ distinguishes underlying characters from grapheme clusters perceived by users.

With PostgreSQL and UTF8 encoding, I can show the representations explicitly:

-- PostgreSQL 18; server_encoding = UTF8
SELECT
    CHAR_LENGTH(U&'\00E9') AS composed_count,
    CHAR_LENGTH(U&'\0065\0301') AS decomposed_count,
    CHAR_LENGTH(normalize(U&'\0065\0301', NFC)) AS normalized_count;

The results are 1, 2 and 1. They demonstrate different representations of similar-looking text and NFC normalisation. This does not mean normalisation solves every problem of counting visible text elements. A length policy must also agree with the form and application using it.

Other engines use different function names

SQL Server uses LEN, which excludes trailing spaces. It is therefore not an unconditional replacement for every measurement above. In SQLite, the basic function name for text is LENGTH; CHAR_LENGTH is not a built-in scalar function.

When migrating a report, I state what its length column measures and which input type it receives. Replacing a function name can produce valid syntax while changing the selected records. Missing values, spaces and combining Unicode text deserve particular attention.

Exercise: define the limit before writing the filter

Predict how ABC, A B, empty text and NULL behave under a minimum of three characters. Then add three spaces. Decide whether that value should be accepted and name the additional rule needed to establish its validity.

Finally, determine whether your export limit concerns characters or bytes. Those numbers differ for Łódź, so the choice has a practical consequence. A length measurement should follow the data contract rather than the first familiar name offered by the editor.

Key takeaways

How many characters does Łódź have?

The spelling shown contains four characters: Ł, ó, d and ź. They occupy seven bytes in UTF-8.

Does LENGTH always count bytes?

No. MySQL 8.4 LENGTH counts bytes and CHAR_LENGTH counts characters. PostgreSQL 18 LENGTH for text counts characters, like CHAR_LENGTH.

Is CHAR_LENGTH enough to validate a name?

It checks length alone. It does not establish that a name is valid, whether spaces alone are acceptable or whether NULL must be rejected.

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.