Introduction to PostgreSQL char Data Type

The char data type is a data type in PostgreSQL used to store fixed-length strings. It can store up to 1GB of data, and its length needs to be specified during definition. When the data length is less than the specified length, the char data type will be padded with spaces. In PostgreSQL, the char data type is similar to the varchar data type, but it does not automatically truncate or pad with spaces.

Syntax

In PostgreSQL, the syntax for defining the char data type is as follows:

CHAR [ (n) ]

where n represents the specified data length.

Use Cases

The char data type is suitable for storing strings with a fixed length. Due to its fixed length, the char data type may perform better in certain scenarios compared to the varchar data type.

Examples

Here are two examples of using the char data type:

Example 1

CREATE TABLE my_table (
    id SERIAL PRIMARY KEY,
    name CHAR(10) NOT NULL
);

INSERT INTO my_table (name) VALUES ('John');
INSERT INTO my_table (name) VALUES ('Mary');
INSERT INTO my_table (name) VALUES ('Tom');

In the above example, we create a table named my_table with two columns, id and name. The name column uses the char(10) data type to store names, which means spaces will be used for padding when storing names.

Example 2

SELECT 'hello'::char(10);

In the above example, we use a SELECT statement to convert the string 'hello' to the char(10) type. Since the length is defined as 10, 5 spaces will be appended after the string.

Conclusion

The char data type is suitable for storing fixed-length strings, and it pads with spaces, ensuring that data occupies a fixed space when stored. However, in certain scenarios, due to the need for space padding, it may result in wasted storage space. Therefore, when choosing between the char and varchar data types, it is necessary to weigh the pros and cons based on the actual situation.