varchar and text
Learning Focus
Use this lesson to choose text vs varchar(n) in PostgreSQL and enforce real business rules without unnecessary migrations.
Overview
In PostgreSQL:
textandvarcharare both variable-length strings.- Performance is typically similar.
Use varchar(n) only when the max length is a real business rule.
Enforcing length
Two equivalent approaches:
name varchar(120) NOT NULL
-- or
name text NOT NULL CHECK (length(name) <= 120)
Case-insensitive text
PostgreSQL extension citext provides a case-insensitive text type:
CREATE EXTENSION IF NOT EXISTS citext;
CREATE TABLE users (
user_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email citext UNIQUE NOT NULL
);