← Back to PostgreSQL Course | Chapter 3: Data Types | Lesson 2 of 7

VARCHAR/TEXT

text stores strings of any length while varchar(n) enforces a maximum length.

In this page:

  1. VARCHAR/TEXT
Syntax
sql
column_name varchar(n)
column_name text

VARCHAR/TEXT

In PostgreSQL text and varchar without a length perform identically, and varchar(n) adds a length check that raises an error when exceeded. char(n) pads with spaces and is rarely useful.

String functions such as LENGTH, UPPER and || (concatenation) work on all three.

Note: Use text unless you truly need a length limit.

Example: VARCHAR/TEXT

sql
CREATE TABLE tags (id INTEGER PRIMARY KEY, code VARCHAR(5), note TEXT);
INSERT INTO tags VALUES (1, 'a1', 'A short note'), (2, 'zz', 'Another, somewhat longer note');
SELECT code, LENGTH(note) AS note_length, UPPER(note) AS shout FROM tags;
SELECT code || ': ' || note AS combined FROM tags;

-- Output:
-- code | note_length | shout
-- a1 | 12 | A SHORT NOTE
-- zz | 29 | ANOTHER, SOMEWHAT LONGER NOTE
-- combined
-- a1: A short note
-- zz: Another, somewhat longer note
Related Topics
Common Mistakes
  1. Using char(n) for variable text
  2. Assuming varchar(n) is faster than text
  3. Forgetting || is concatenation
Chapter Summary
  • text has no length limit
  • varchar(n) enforces a maximum
  • char(n) pads with spaces
  • || concatenates strings
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.