SQL CHAR_LENGTH function
Returns the number of characters in a string, however many bytes each one occupies.
- Categoria
- Strings
- Returns
integer- In this category
- 133 of 172
Sintaxe
CHAR_LENGTH(string)
CHARACTER_LENGTH(string)
Each block is a separate form. The support table and the examples show which engine takes which.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Different name or syntax | No CHAR_LENGTH; LEN(v) counts characters but ignores trailing spaces. |
| PostgreSQL | Sim | Supported under this name. |
| MySQL | Sim | Supported under this name. |
| SQLite | Different name or syntax | No CHAR_LENGTH; length(x) counts characters for text. |
| Oracle | Different name or syntax | No CHAR_LENGTH; LENGTH counts characters. |
Exemplos
PostgreSQL
SELECT CHAR_LENGTH('héllo') AS chars; -- 5
MySQL
SELECT CHAR_LENGTH(name) AS chars, LENGTH(name) AS bytes FROM products;
SQL Server
SELECT LEN(name) AS chars FROM products;
Bom saber
- Characters, not bytes: 'héllo' is 5 characters and 6 UTF-8 bytes, and an emoji is 1 character and 4 bytes.
- SQL Server's LEN ignores trailing spaces (LEN('ab ') is 2), while the other engines count them. DATALENGTH counts bytes including the spaces.
- CHARACTER_LENGTH is the standard spelling and an exact synonym in PostgreSQL and MySQL. MySQL's LENGTH is not a synonym: it counts bytes.
Questions about CHAR_LENGTH
Why does my emoji count as one character but more bytes?
CHAR_LENGTH counts code points; an emoji is one code point encoded as four UTF-8 bytes, so OCTET_LENGTH reports 4.
Is CHAR_LENGTH the same as LEN in SQL Server?
Close: LEN counts characters but drops trailing spaces, and under non-_SC collations it counts an emoji as 2. MySQL's CHAR_LENGTH counts every character, spaces included.
Is there a difference between CHAR_LENGTH and CHARACTER_LENGTH?
No. They are synonyms; CHARACTER_LENGTH is the SQL-standard name, CHAR_LENGTH the common short form.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: MySQL, SQL Server, PostgreSQL, SQLite, Oracle.
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.