postgresql
  1. postgresql-varchar

VARCHAR - (PostgreSQL Data Types)

In PostgreSQL, VARCHAR is used as a variable-length character string data type. It is used to store alphanumeric or textual data which is of variable length. In this tutorial, we will discuss the syntax, example, output, explanation, use, important points, and summary of VARCHAR data type in PostgreSQL.

Syntax

The syntax to create a column of type VARCHAR is as follows:

column_name VARCHAR(n)

Here, column_name is the name of the column and n is the maximum number of characters that the column can hold.

Example

Let's create a table using the VARCHAR data type.

CREATE TABLE books (
    id SERIAL PRIMARY KEY,
    title VARCHAR(50),
    author VARCHAR(30),
    publisher VARCHAR(30),
    published_date VARCHAR(20)
);

Here, we created a table named books. We created columns title, author, publisher, and published_date as VARCHAR data type, with different maximum lengths.

Output

After executing the above SQL statement, the books table is created with the specified columns.

Explanation

In the above example, we used the VARCHAR data type to create columns for a book. Every column is of variable length, so we specified the maximum length each column can hold.

Use

The VARCHAR data type in PostgreSQL is used to store variable-length strings or text data, such as names or descriptions. The maximum length of the data that can be stored in a VARCHAR column is determined by the n parameter passed during column creation.

Important Points

  • The maximum length of a VARCHAR data type is 65,535 bytes.
  • When using VARCHAR data type, the actual amount of memory required to store the data depends on the length of the string.
  • PostgreSQL allows the use of TEXT data type to store longer strings, and is similar to VARCHAR but with no maximum limit.
  • VARCHAR data type can be used in index and query optimization as it uses less space compared to TEXT data type.

Summary

In this tutorial, we discussed the VARCHAR data type in PostgreSQL. We covered the syntax, example, output, explanation, use, and important points of VARCHAR data type. With this knowledge, you can now use the VARCHAR data type in PostgreSQL databases to store variable-length strings or text data with a specified maximum length.

Published on: