WikiGalaxy

Personalize

PostgreSQL VarChar

Understanding VarChar in PostgreSQL

In PostgreSQL, the VarChar data type is used to store variable-length character strings. It is similar to the Text data type but with a limit on the number of characters that can be stored.


String createTableSQL = "CREATE TABLE employees ("
    + "employee_id SERIAL PRIMARY KEY, "
    + "first_name VARCHAR(50), "
    + "last_name VARCHAR(50), "
    + "email VARCHAR(100));";
        

Defining VarChar with Length

When defining a VARCHAR column, you specify a maximum length. For example, VARCHAR(50) indicates a maximum of 50 characters.


String alterTableSQL = "ALTER TABLE employees "
    + "ADD COLUMN middle_name VARCHAR(30);";
        

VarChar vs Text

The Text data type can store strings of any length, making it more flexible than VarChar for strings without a defined length constraint.


String createDocumentsTableSQL = "CREATE TABLE documents ("
    + "document_id SERIAL PRIMARY KEY, "
    + "title TEXT, "
    + "content TEXT);";
        

Using VarChar in Indexes

VarChar columns can be indexed, which can improve query performance when searching or filtering by these columns.


String createIndexSQL = "CREATE INDEX idx_employee_email ON employees(email);";
        

Handling VarChar Length Exceedance

If a string exceeds the specified VarChar length, PostgreSQL will throw an error during insertion or update.


String insertEmployeeSQL = "INSERT INTO employees (first_name, last_name, email) "
    + "VALUES ('John', 'Doe', 'john.doe@example.com');";
        

VarChar without Length

A VarChar column can be defined without specifying a length, effectively behaving like a Text type.


String createMessagesTableSQL = "CREATE TABLE messages ("
    + "message_id SERIAL PRIMARY KEY, "
    + "sender VARCHAR, "
    + "receiver VARCHAR, "
    + "body TEXT);";
        

Console Output:

INSERT 0 1

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025