PostgreSQL – VARCHAR Data Type

The varchar data type is used to store variable-length character strings. Unlike the char data type, which stores strings of fixed length, the varchar data type can store strings of varying lengths without padding. Here are some key points about the varchar data type:

  1. Variable Length: The varchar data type allows you to store strings of different lengths. It doesn’t pad the stored strings with spaces.
  2. Size: The storage size for a varchar column varies based on the length of the stored string. The storage size includes the actual data and some additional overhead.
  3. Comparison and Trimming: When comparing varchar values, PostgreSQL does not consider trailing spaces. It treats strings with the same characters but different spaces as equal. If you want to preserve the spaces for comparison, you might need to use functions like LIKE or ILIKE.

Here’s an example of using the varchar data type:

CREATE TABLE product_names 
( product_id serial PRIMARY KEY, 
product_name varchar(100)
); 
INSERT INTO product_names (product_name) 
VALUES ('Widget A'); 
SELECT * FROM product_names 
WHERE product_name = 'Widget A';

In this example, a product_name column of type varchar is used to store product names of varying lengths. The varchar data type is suitable when you want to allow flexible string lengths without the constraint of a fixed length like the char data type.

Similar Posts