Character types store text data in a database. They help keep words, names, or any text information organized and easy to find.
Character types (char, varchar, text) in PostgreSQL
CHAR(n) VARCHAR(n) TEXT
CHAR(n) stores fixed-length text, padded with spaces if shorter.
VARCHAR(n) stores variable-length text up to n characters.
TEXT stores variable-length text with no specific limit.
CREATE TABLE example ( code CHAR(3), name VARCHAR(50), description TEXT );
INSERT INTO example (code, name, description) VALUES ('USA', 'United States', 'A country in North America.');
SELECT code, name FROM example WHERE name LIKE 'United%';
This example creates a table for countries with a fixed 3-letter code, a name up to 50 characters, and notes with no length limit. It inserts three countries and then selects all data ordered by the country code.
CREATE TABLE countries ( country_code CHAR(3), country_name VARCHAR(50), notes TEXT ); INSERT INTO countries (country_code, country_name, notes) VALUES ('USA', 'United States', 'Located in North America'), ('CAN', 'Canada', 'Known for maple syrup'), ('MEX', 'Mexico', 'Famous for its cuisine'); SELECT country_code, country_name, notes FROM countries ORDER BY country_code;
CHAR pads text with spaces to fill the fixed length, so 'USA' stored as CHAR(5) becomes 'USA '.
VARCHAR is more flexible and usually preferred unless you need fixed length.
TEXT can store very long text but does not enforce length limits.
CHAR(n) stores fixed-length text, padding with spaces if needed.
VARCHAR(n) stores variable-length text up to n characters.
TEXT stores variable-length text with no size limit.