PostgreSQL – CHAR Data Type

In PostgreSQL, the char data type, also known as the fixed-length character string type, is used to store strings of fixed length. It’s important to note that the char type is not the same as the variable-length character string type (varchar). Here are some key points about the char data type:

  1. Fixed Length: The char data type stores strings of a specific length that you define when creating the column. Any string stored in a char column will be padded with spaces to match the defined length.
  2. Padding: If the stored string is shorter than the defined length, PostgreSQL adds trailing spaces to pad it to the specified length. If the string is longer, PostgreSQL will truncate it.
  3. Size: The storage size for a char column is fixed and depends on the defined length. For example, a char(10) column will always take up 10 bytes of storage.
  4. Comparison and Trimming: When comparing char values, PostgreSQL considers trailing spaces. If you want to perform a comparison without considering the padding, you might need to use functions like TRIM().

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

CREATE TABLE product_codes 
(product_id serial PRIMARY KEY, 
product_code char(6)
); 
INSERT INTO product_codes (product_code) 
VALUES ('ABC123');
SELECT * FROM product_codes 
WHERE product_code = 'ABC123';

In this example, a product_code column of type char is used to store product codes. The char data type is suitable when you want to enforce a fixed length for strings, but be cautious about padding and trimming when comparing values.

Similar Posts