The LENGTH() function in MySQL returns the length of a string in bytes. For ASCII characters, this equals the number of characters, but for multibyte characters (like UTF-8), the byte count can exceed the character count. Use CHAR_LENGTH() when you need the number of characters instead.
What LENGTH() Actually Does
LENGTH(str) takes a string argument and returns an integer representing the number of bytes in that string. The argument can be a string literal, a column value, or an expression that evaluates to a string. If the argument is NULL, the result is NULL.
Here is a simple example:
SELECT LENGTH('hello'); -- Returns 5
SELECT LENGTH('héllo'); -- Returns 6 (in utf8mb4, é is 2 bytes)
SELECT LENGTH(''); -- Returns 0
SELECT LENGTH(NULL); -- Returns NULL
The function is case-sensitive in the sense that it does not alter the string; it only counts bytes. It works on CHAR, VARCHAR, TEXT, and BLOB data types.
Byte Length vs. Character Length
MySQL stores strings in various character sets. The default character set for a database or table determines how many bytes each character occupies. For single-byte character sets like latin1, one character = one byte, so LENGTH() and CHAR_LENGTH() return the same number.
For multibyte character sets like utf8mb4 (the common UTF-8 encoding in MySQL), a character can take 1 to 4 bytes. For example, the letter ‘A’ is 1 byte, ‘é’ is 2 bytes, ‘€’ is 3 bytes, and some emoji are 4 bytes. In such cases:
LENGTH('€')returns 3CHAR_LENGTH('€')returns 1
If you are validating input length for user-facing fields (like a username), use CHAR_LENGTH() to count characters, not bytes. Use LENGTH() when you need to know storage size or when working with binary data.
How to Use LENGTH() in Queries
You can use LENGTH() in SELECT, WHERE, ORDER BY, and GROUP BY clauses. Here are practical examples:
-- Find all products with names longer than 20 characters
SELECT product_name
FROM products
WHERE LENGTH(product_name) > 20;
-- Order customers by the length of their last name
SELECT last_name
FROM customers
ORDER BY LENGTH(last_name) DESC;
-- Count how many users have a password hash of a certain length
SELECT COUNT(*) AS users_with_64_char_hash
FROM users
WHERE LENGTH(password_hash) = 64;
You can also use it in expressions, such as concatenating with other functions:
SELECT CONCAT('Length: ', LENGTH(description)) AS length_label
FROM articles;
Common Use Cases and Examples
Here are typical scenarios where LENGTH() is used:
- Data validation: Checking that a field meets a minimum or maximum byte length before processing.
- Truncation logic: Deciding whether a string needs to be truncated before display or storage.
- Storage estimation: Calculating how much space a column will consume, especially for
BLOBorTEXTfields. - Finding anomalies: Detecting rows with unusually long or short values, which might indicate corruption or invalid input.
For example, to find all blog posts where the body text is longer than 10,000 bytes (which might indicate a problem if your column is VARCHAR(10000)):
SELECT id, title
FROM posts
WHERE LENGTH(body) > 10000;
LENGTH() vs. CHAR_LENGTH() vs. BIT_LENGTH()
MySQL offers several length-related functions. Knowing the difference helps you choose the right one:
LENGTH(str)– byte count.CHAR_LENGTH(str)– character count (also calledCHARACTER_LENGTH()).BIT_LENGTH(str)– bit count (byte count × 8).
Example with a UTF-8 string containing ‘é’:
SELECT LENGTH('é') AS bytes, -- 2
CHAR_LENGTH('é') AS chars, -- 1
BIT_LENGTH('é') AS bits; -- 16
Use BIT_LENGTH() rarely, usually for low-level network or storage calculations.
Performance and Indexing Considerations
Using LENGTH() in a WHERE clause can prevent the query from using an index on that column, because the function must be evaluated for every row. This is called a non-sargable condition. For example, WHERE LENGTH(name) = 5 will scan the whole table if name is indexed, because the index stores the actual values, not their lengths.
If you frequently filter by length, consider adding a generated column that stores the length, and index that column. For example:
ALTER TABLE users
ADD name_length INT GENERATED ALWAYS AS (CHAR_LENGTH(name)) STORED,
ADD INDEX idx_name_length (name_length);
Then query with WHERE name_length = 5 to use the index.
Frequently Asked Questions
Does LENGTH() count spaces and special characters?
Yes, LENGTH() counts every byte in the string, including spaces, tabs, newlines, and punctuation. For example, LENGTH('a b') returns 3 because there are three bytes (a, space, b).
Why does LENGTH() return 2 for the character ‘é’?
Because in the utf8mb4 character set, the character ‘é’ is encoded as two bytes. If your column uses a single-byte character set like latin1, LENGTH('é') would return 1. Always check the column’s character set with SHOW CREATE TABLE or INFORMATION_SCHEMA.
Can I use LENGTH() on numbers or dates?
Yes, MySQL implicitly converts numbers and dates to strings when you pass them to LENGTH(). For example, LENGTH(12345) returns 5, and LENGTH(CURDATE()) returns 10 (the default date format is ‘YYYY-MM-DD’). However, it’s clearer to cast explicitly: LENGTH(CAST(12345 AS CHAR)).
What is the difference between LENGTH() and CHAR_LENGTH() in MySQL?
LENGTH() returns the number of bytes, while CHAR_LENGTH() returns the number of characters. For single-byte character sets they are identical. For multibyte character sets, CHAR_LENGTH() is usually what you want for user-facing validation.
Is there a way to get the length of a string in words?
MySQL does not have a built-in word-count function. You can approximate it by counting spaces: LENGTH(str) - LENGTH(REPLACE(str, ' ', '')) + 1, but this breaks with multiple spaces or punctuation. For accurate word counts, you would need a full-text parser or a custom function.
Does LENGTH() work with BLOB data?
Yes, LENGTH() works on binary strings and BLOB columns, returning the number of bytes. This is useful for checking file sizes stored in the database.
Practical Example: Validating Input
Suppose you have a registration form and want to ensure usernames are between 3 and 20 characters, not bytes. You can enforce this in an INSERT trigger or application code. Here is a query to check existing data:
SELECT username,
CHAR_LENGTH(username) AS char_len,
LENGTH(username) AS byte_len
FROM users
WHERE CHAR_LENGTH(username) < 3 OR CHAR_LENGTH(username) > 20;
This finds any usernames that violate the rule. If you mistakenly used LENGTH(), a username with 20 emoji characters would pass (byte length 80) but be too long visually.
Conclusion
LENGTH() is a straightforward function, but its byte-based behavior often surprises developers who assume it counts characters. Always consider the character set of your data and whether you need byte length or character length. For most text validation, CHAR_LENGTH() is the safer choice. Use LENGTH() when you truly need storage size or are working with binary data.
Related
- Shortcut for Italics? Keyboard & Word Tips
- How to Create a Fan Number in Excel
- Java Code to Split String: Methods & Examples
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- IFERROR in Excel: How to Catch and Handle Formula ErrorsTo use IFERROR in Excel, wrap a calculation or formula in IFERROR and choose what to show if…
- Oracle RIGHT Function: How to Get Trailing CharactersOracle Database does not provide a built-in RIGHT() string function. To return the last characters of a string,…
- Half Day Attendance Formula in Excel: Examples and SetupFor a row of attendance codes in B2:F2, where P means present and H means half day, use…
- Excel Named Range vs Table: How to Choose the Right ToolAn Excel named range gives a cell or formula a memorable name; an Excel table organizes related records…
- Add a Subtotal Row to an Excel Table the Right WayTo add a total row to an Excel table in Microsoft 365 for Windows, click anywhere in the…
- DAX Formula to Concatenate Text in Power BIIn Power BI, use the DAX & operator to join text: Customers[FirstName] & " " & Customers[LastName]. Use…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.