SoFunction
Updated on 2025-04-08

postgresql column type operation

Get used to Oracle:

ALTER TABLE Table name ALTER COLUMN Column name New data type [(length)] NULL or NOT NULL

When this modification method is used, in pg:

highgo=# create table p1 (id int,pswd varchar(30),time timestamp);
CREATE TABLE
highgo=# insert into p1 select generate_series(1,500000),md5('random()::text'),clock_timestamp();

Error: The value is too long for variable character types (30)

Will you find that it cannot be added successfully?

highgo=# alter table p1 alter column pswd text NULL;

Error: Syntax error in or near "text"

LINE 1: alter table p1 alter column pswd text NULL;

Let's take a look at the syntax in pg:

highgo=# \h auto
where action is one of: 
 
 ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ]
 DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ]
 ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]
 ALTER [ COLUMN ] column_name SET DEFAULT expression
highgo=# alter table p1 alter COLUMN pswd type text ;
ALTER TABLE
highgo=# \d p1
       Table "public.p1"
 Column |   Type    | Collation | Nullable | Default 
--------+-----------------------------+-----------+----------+---------
 id  | integer      |   |   | 
 pswd | text      |   |   | 
 time | timestamp without time zone |   |   | 

success!

Supplement: postgresql modify the field type to array type (text is changed to text[])

grammar:

alter table tablename alter columnname type oldcolumntype USING columnname:: newcolumntype

eg:

alter table dirty_track alter labels type text USING labels::text[];

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.