length(text) — Number of characters in a string
Last updated: 2026-11-04
length(text) — Number of characters in a string
length() returns the number of characters in a string, and is the workhorse for input validation, truncation and display-width checks. On text it counts characters rather than bytes, so one Chinese character counts as 1; use octet_length() when you need the byte count instead.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
length(string text) → integer
⚙️ Parameters
| string text | The string to measure. Type text; if a bytea is passed instead, the byte count is returned. |
|---|
Returns:integer — the number of characters (text) or bytes (bytea). Returns NULL for a NULL input.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | uname | char_len | byte_len
----+-------+----------+----------
1 | alice | 5 | 5
2 | bob | 3 | 3
3 | 张三 | 2 | 6
(3 rows)
📌 Key Points
- length() counts characters while octet_length() counts bytes — one Chinese character occupies 3 bytes in UTF-8, so the two can differ a lot.
- With a bytea input length() returns the byte count, and char_length() has no bytea version at all, so cast to text if you need a character count.
- A NULL input yields NULL; wrap the call in coalesce() when you need a fallback value.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QDoes length('机械键盘') return 3 or 9?
AIt returns 3 — length() counts characters, and one Chinese character is one character. Use octet_length() for the byte count, which is 9 in UTF-8.