SQL emoji and string length
Emoji break the characters-equal-bytes assumption everywhere: lengths differ by function, storage needs utf8mb4 or nvarchar, and some engines split them in half.
- Categoría
- Strings
- Returns
integer- In this category
- 49 of 172
Sintaxis
SELECT LENGTH('😀') -- 1, 2 or 4 depending on engine and function
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | Supported under this name. |
| SQLite | Sí | Supported under this name. |
| Oracle | Sí | Supported under this name. |
Ejemplos
SQL Server
SELECT LEN(N'😀') AS units, DATALENGTH(N'😀') AS bytes; -- 2, 4
PostgreSQL
SELECT length('😀') AS chars, octet_length('😀') AS bytes;
-- 1, 4
Oracle
SELECT LENGTH('😀') AS chars, LENGTH2('😀') AS units, LENGTHB('😀') AS bytes FROM dual;
-- 1, 2, 4 in an AL32UTF8 database
Conviene saberlo
- SQL Server: LEN(N'😀') is 2 (UTF-16 code units) and DATALENGTH is 4 bytes, unless the collation is supplementary-aware (_SC or _140), where LEN is 1. Storage needs nvarchar, or varchar with a UTF-8 collation (2019+).
- MySQL: needs utf8mb4 (utf8mb3 rejects the insert), then CHAR_LENGTH('😀') is 1 and LENGTH is 4 bytes.
- PostgreSQL: length('😀') is 1 and octet_length is 4. SQLite: length('😀') is 1.
- Oracle: in an AL32UTF8 VARCHAR2, LENGTH is 1, LENGTH2 is 2 (UTF-16 units) and LENGTHB is 4. NVARCHAR2 data stores UTF-16, so LENGTH there is 2.
Questions about Emoji and string length
Why does my emoji insert fail?
The column or connection is not 4-byte capable: MySQL utf8mb3, or SQL Server varchar without a UTF-8 collation. Move to utf8mb4 or nvarchar end to end.
Why is LEN of an emoji 2?
SQL Server's LEN counts UTF-16 code units, and an emoji is a surrogate pair. A supplementary-character collation (_SC or _140) makes it count 1, as PostgreSQL, MySQL's CHAR_LENGTH and SQLite already do.
Can a string function split an emoji in half?
Yes: SQL Server's SUBSTRING and LEFT under a non-SC collation, and Oracle's SUBSTR on NVARCHAR2, can cut between the surrogate halves and leave a broken character.
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: SQL Server, PostgreSQL, MySQL, 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.