// strings reference

SQL LENGTHB function

Byte count under the database charset: the number storage limits actually enforce when VARCHAR2 semantics are bytes.

类别
Strings
Returns
integer
In this category
46 of 172

语法

LENGTHB(string)

引擎支持

引擎Support备注
SQL Server Not built in No built-in equivalent.
PostgreSQL Not built in No built-in equivalent.
MySQL Not built in No built-in equivalent.
SQLite Not built in No built-in equivalent.
Oracle 是 Supported under this name.

示例

Oracle

SELECT LENGTHB('é') AS bytes, LENGTH('é') AS chars FROM dual;
-- 2, 1

Oracle

SELECT LENGTH4('😀') AS codepoints, LENGTH2('😀') AS utf16_units, LENGTHB('😀') AS bytes FROM dual;
-- 1, 2, 4

值得了解

  • The family: LENGTH (characters in the input's character set), LENGTHB (bytes), LENGTHC (complete Unicode characters), LENGTH2 (UTF-16 code units), LENGTH4 (code points).
  • Under AL32UTF8, LENGTHB('é') is 2 and LENGTH('é') is 1. An emoji in a VARCHAR2 is LENGTH 1, LENGTH2 2, LENGTH4 1 and LENGTHB 4; in an NVARCHAR2 (AL16UTF16) plain LENGTH counts it as 2.
  • It reflects the database character set, not the client's: the same data has different LENGTHB values in different databases.
  • VARCHAR2(n) without CHAR or NLS_LENGTH_SEMANTICS=CHAR limits bytes; LENGTHB is the check that mirrors what INSERT enforces.

Questions about LENGTHB

How is LENGTHB different from LENGTH in Oracle?

LENGTH counts characters; LENGTHB counts encoded bytes under the database charset. Accents and emoji are where they diverge.

Why does LENGTH count an emoji as 2?

The value is NVARCHAR2, stored as AL16UTF16, where an emoji is a surrogate pair. On VARCHAR2 in an AL32UTF8 database LENGTH gives 1. LENGTH4 gives 1 for both.

What should I check before a VARCHAR2 insert?

LENGTHB under byte semantics: it is the only measure that matches what the column will enforce on insert.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: Oracle.

// fewer lookups

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.