Open In App

PostgreSQL – CHAR Data Type

Improve
Improve
Like Article
Like
Save
Share
Report

PostgreSQL supports a character data type called CHAR. This data type is used to store character of limited length. It is represented as char(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to char(1) or character(1). Any attempt to store a longer string in the column that defined with char(n) results in PostgreSQL issuing an error. However, one exception is that if the excess characters are all spaces, PostgreSQL will truncate the spaces to the maximum length and store the string.

Syntax: variable_name CHAR(n)

Example :
Let’s create a new table(say, char_test) for the demonstration using the below commands:

CREATE TABLE char_test (
    id serial PRIMARY KEY,
    x CHAR (1),
        y CHAR(10)
);

Now let’s insert a new row into the char_test table using the below command:

INSERT INTO char_test (x, y)
VALUES
    (
        'Geeks',
        'This is a test for char'
        
    );

At this stage PostgreSQL will raise an error as the data type of the x column is char(1) and we tried to insert a string with three characters into this column as shown below:

ERROR:  value too long for type character(1)

So, now let’s fix it.

INSERT INTO char_test (x, y)
VALUES
    (
        'G',
        'This is a test for char'
        
    );

Now, we will get the same error for the y column as the number of characters entered is greater than 10 as shown below:

ERROR:  value too long for type character(10)


Let’s fix it too.

INSERT INTO char_test (x, y)
VALUES
    (
        'G',
        'hello Geek'
        
    );

Now that we have managed to successfully assign the values to the character data type, check it by running the below command:

SELECT * FROM char_test;

Output:


Last Updated : 28 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads