Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql change character varying to character varying array

Tags:

sql

postgresql

below I have two columns in table. they both say they are character varying but zoning_description has an array symbol after it. I need to change the zoning column to match the zoning_description column type. how do I accomplish this.

Also what is the difference between these two column types... I am running into an error later in a different process because of this problem

enter image description here

like image 390
ziggy Avatar asked Oct 15 '25 16:10

ziggy


2 Answers

just alter type with casting, eg your table:

t=# create table z as select '{R}'::varchar zoning, '{"Blah-ah ah"}'::varchar[] zoning_description;
SELECT 1
t=# select * from z;
 zoning | zoning_description
--------+--------------------
 {R}    | {"Blah-ah ah"}
(1 row)

alter type:

t=# alter table z alter column zoning type varchar[] using zoning::varchar[];
ALTER TABLE
t=# select * from z;
 zoning | zoning_description
--------+--------------------
 {R}    | {"Blah-ah ah"}
(1 row)

checking columns:

t=# \d z
                            Table "postgres.z"
       Column       |        Type         | Collation | Nullable | Default
--------------------+---------------------+-----------+----------+---------
 zoning             | character varying[] |           |          |
 zoning_description | character varying[] |           |          |
like image 114
Vao Tsun Avatar answered Oct 17 '25 06:10

Vao Tsun


It looks like zoning_description is an array of VARCHAR values, while zoning is just a VARCHAR. If you want to convert zoning to be the same data type as zoning_description, you can just do:

SELECT ARRAY[zoning]

This will CAST it as an array data type.

Working query

SELECT 
    MyVarchar, 
    PG_TYPEOF(MyVarchar),  -- character varying
    MyVarcharArray, 
    PG_TYPEOF(MyVarcharArray),  -- character varying[]
    ARRAY[MyVarchar], 
    PG_TYPEOF(ARRAY[MyVarchar])  -- character varying[]
FROM (
    SELECT 
    CAST('rammstein' AS VARCHAR) AS MyVarchar, 
    ARRAY[CAST('du hast' AS VARCHAR)] AS MyVarcharArray
) src
like image 31
ravioli Avatar answered Oct 17 '25 06:10

ravioli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!