SQL VARCHAR length semantics
The same declaration enforces different limits per engine, which is why a 50-char field migrates fine and then truncates on real names.
- Categoria
- Strings
- Returns
string- In this category
- 48 of 172
Sintaxe
VARCHAR2(50 CHAR) -- Oracle: characters, not bytes
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | Supported under this name. |
| PostgreSQL | Sim | Supported under this name. |
| MySQL | Sim | Supported under this name. |
| SQLite | Sim | Supported under this name. |
| Oracle | Sim | Supported under this name. |
Exemplos
Oracle
CREATE TABLE names (name VARCHAR2(50 CHAR)); -- 50 characters, not bytes
SQL Server
SELECT LEN('héllo') AS chars, DATALENGTH('héllo') AS bytes;
-- 5, 5 under a Latin1 collation; 5, 6 under a UTF-8 (_UTF8) collation
PostgreSQL
SELECT length('héllo') AS chars, octet_length('héllo') AS bytes;
-- 5, 6
Bom saber
- MySQL VARCHAR(n) and PostgreSQL VARCHAR(n) count characters; SQL Server VARCHAR(n) counts bytes (NVARCHAR(n) counts UTF-16 code units).
- Oracle VARCHAR2(n) is bytes by default; VARCHAR2(n CHAR) opts into characters, and NLS_LENGTH_SEMANTICS sets the database default.
- SQLite declares lengths but does not enforce them: any string fits any column.
- Overflow behaviour differs too: MySQL strict mode and SQL Server and PostgreSQL all error on insert; permissive MySQL truncates with a warning.
Questions about VARCHAR(n): chars or bytes?
Why did my VARCHAR(50) reject a 50-character name?
SQL Server varchar counts bytes and Oracle VARCHAR2 defaults to bytes; accented or non-Latin characters cost more than one each. Switch to nvarchar, or VARCHAR2(50 CHAR).
Does NVARCHAR(n) count characters?
It counts UTF-16 code units: one for most characters, two for emoji and other supplementary characters. Close enough to characters until emoji appear.
Is VARCHAR(n) enforced in SQLite?
No. SQLite accepts any length regardless of the declared n. Constraints there are app-level or via CHECK(length(col) <= n).
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- CHAR versus VARCHAR semantics in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
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.