← Back to SQL, page 9

sql-0170 · Easy fresher

A column is declared VARCHAR(3). What happens when you insert 'abcdef' in SQLite and in PostgreSQL?

SQLite ignores the length and stores all six characters, because VARCHAR(3) only sets TEXT affinity. PostgreSQL raises an error that the value is too long for character varying(3). Use a CHECK on length() to enforce limits in SQLite.

Full answer
sql
CREATE TABLE v (code VARCHAR(3));
INSERT INTO v VALUES ('abcdef');
SELECT code, length(code) AS len FROM v;
codelen
abcdef6
sql
CREATE TABLE v (code VARCHAR(3));
INSERT INTO v VALUES ('abcdef');
-- error on purpose
text
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 purpose
text
Error: CHECK constraint failed: length(code) <= 3

Lengths 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