Reputation: 319
I have table A(colmn1 varchar(10),column2 varchar2(20));
but I need to convert the datatype varchar
to text[] array
table A(column1 text[],column2 text[])
please tell me how to alter this table columns
Upvotes: 2
Views: 3754
Reputation: 458
This works and it also makes sure that you dont create values that are arrays with a null element in.
ALTER TABLE myTable ALTER COLUMN myColumn TYPE varchar[] USING CASE WHEN myColumn IS null THEN null ELSE array[myColumn] END;
Upvotes: 1
Reputation: 1498
To convert a column to a different data type, use a command like this:
ALTER TABLE TableName ALTER COLUMN ColumnName TYPE text[] Using array[ColumnName];;
This will succeed only if each existing entry in the column can be converted to the new type by an implicit cast. If a more complex conversion is needed, you can add a USING clause that specifies how to compute the new values from the old.
PostgreSQL will attempt to convert the column's default value (if any) to the new type, as well as any constraints that involve the column. But these conversions may fail, or may produce surprising results. It's often best to drop any constraints on the column before altering its type, and then add back suitably modified constraints afterwards.
Upvotes: 1
Reputation: 895
do you really want text[]??? 'text' can save string. you don't need text[].
postgresql doc is like below
In addition, PostgreSQL provides the text type, which stores strings of any length. Although the type text is not in the SQL standard, several other SQL database management systems have it as well.
so you just type below
ALTER TABLE TableName ALTER COLUMN ColumnName TYPE text;
Upvotes: 2
Reputation: 434595
There is no implicit cast that will convert your varchar
to a text[]
so you'll need to specify how the conversion should be done with a USING clause:
The optional
USING
clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. AUSING
clause must be provided if there is no implicit or assignment cast from old to new type.
Something simple like this should do the trick:
alter table A alter column column1 type text[] using array[column1];
Similarly for the other column.
Upvotes: 4