SQL LENGTH function
Returns how long a string is. The catch is the unit: LEN and LENGTH usually count characters, but MySQL's LENGTH counts bytes, which differs as soon as accents or emoji appear.
- 카테고리
- Strings
- Returns
integer- In this category
- 3 of 172
구문
LEN(string) -- SQL Server
LENGTH(string)
CHAR_LENGTH(string)
Each block is a separate form. The support table and the examples show which engine takes which.
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| SQL Server | Different name or syntax | spelled LEN; ignores trailing spaces; DATALENGTH counts bytes |
| PostgreSQL | 예 | Supported under this name. |
| MySQL | Different name or syntax | LENGTH counts bytes, CHAR_LENGTH counts characters |
| SQLite | 예 | Supported under this name. |
| Oracle | 예 | Supported under this name. |
예시
PostgreSQL
-- LENGTH counts characters on PostgreSQL, SQLite and Oracle
SELECT LENGTH('héllo') AS chars; -- 5
MySQL
SELECT LENGTH('héllo') AS bytes, CHAR_LENGTH('héllo') AS chars;
-- 6, 5
알아 두면 좋은 정보
- MySQL: LENGTH('é') is 2 (UTF-8 bytes), CHAR_LENGTH('é') is 1. Use CHAR_LENGTH for user-visible text.
- SQL Server's LEN ignores trailing spaces: LEN('ab ') is 2. DATALENGTH keeps them but counts bytes, so DATALENGTH(N'ab ') is 6.
- PostgreSQL has LENGTH and CHAR_LENGTH (characters) and OCTET_LENGTH (bytes). Oracle's LENGTH counts characters and LENGTHB counts bytes. SQLite's LENGTH counts characters for text and bytes for blobs.
Questions about LENGTH / LEN
Does LENGTH count characters or bytes?
On MySQL, bytes, so 'é' counts as 2 and an emoji as 4. CHAR_LENGTH counts characters. PostgreSQL's LENGTH counts characters and OCTET_LENGTH counts bytes.
Why does LEN ignore my trailing spaces?
SQL Server's LEN excludes trailing spaces by design. DATALENGTH does not, but counts bytes, not characters.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Find rows containing control characters Snippet
- Find values truncated at the max length Snippet
- Natural sort strings with numbers in SQL Snippet
- Ellipsize long text with a trailing ellipsis in SQL Snippet
- Validate phone number shape Snippet
- Count how many times a substring appears in SQL Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite, Oracle, MySQL.
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.