Full answer
sql
CREATE TABLE v (code VARCHAR(3));
INSERT INTO v VALUES ('abcdef');
SELECT code, length(code) AS len FROM v;| code | len |
|---|---|
| abcdef | 6 |
sql
CREATE TABLE v (code VARCHAR(3));
INSERT INTO v VALUES ('abcdef');
-- error on purposetext
Error: value too long for type character varying(3)In PostgreSQL, text and varchar without a length perform the same; varchar(n) adds a length check and nothing else. Many teams use text with a CHECK constraint, which can be changed later without rewriting the column type.
In SQLite, enforce the limit explicitly:
sql
CREATE TABLE v2 (code TEXT CHECK (length(code) <= 3));
INSERT INTO v2 VALUES ('abcdef');
-- error on purposetext
Error: CHECK constraint failed: length(code) <= 3Lengths count characters on both engines, not bytes, so 'café' has length 4. When data moves from SQLite to PostgreSQL, values that were silently accepted can make the import fail, so check MAX(length(col)) before migrating.
sql
CREATE TABLE v (code VARCHAR(3));
INSERT INTO v VALUES ('abcdef');
SELECT code, length(code) AS len FROM v;
-- error on purpose
CREATE TABLE v2 (code TEXT CHECK (length(code) <= 3));
INSERT INTO v2 VALUES ('abcdef');Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- SQLite ignores VARCHAR lengths
- PostgreSQL enforces varchar(n) and errors on longer values
- text and varchar perform the same in PostgreSQL
- Use CHECK (length(col) <= n) in SQLite
Common mistakes
- Relying on VARCHAR(n) to validate data in SQLite
- Choosing tiny lengths that later need migrations
Follow-ups
- What does CHAR(n) do with shorter values in PostgreSQL?
- How would you limit a username to 20 characters on both engines?
Tips
- State both engine results plainly