Hett
Hett

Reputation: 2433

Empty array as PostgreSQL array column default value

I have a defined an array field in postgresql 9.4 database:

character varying(64)[]

Can I have an empty array e.g. {} for default value of that field? What will be the syntax for setting so?

I'm getting following error in case of setting just brackets {}:

SQL error:

ERROR:  syntax error at or near "{"
LINE 1: ...public"."accounts" ALTER COLUMN "pwd_history" SET DEFAULT {}
                                                                     ^

In statement:
ALTER TABLE "public"."accounts" ALTER COLUMN "pwd_history" SET DEFAULT {}

Upvotes: 132

Views: 122678

Answers (3)

Burak
Burak

Reputation: 2117

It threw an error where it can not find SET. This worked for me.

ALTER TABLE public.accounts 
    ALTER COLUMN pwd_history DEFAULT array[]::varchar[];

Upvotes: 7

GollyJer
GollyJer

Reputation: 26672

I tested both the accepted answer and the one from the comments. They both work.
I'll graduate the comments to an answer as it's my preferred syntax. 🙂

ALTER TABLE public.accounts 
    ALTER COLUMN pwd_history SET DEFAULT '{}';

Upvotes: 77

user330315
user330315

Reputation:

You need to use the explicit array initializer and cast that to the correct type:

ALTER TABLE public.accounts 
    ALTER COLUMN pwd_history SET DEFAULT array[]::varchar[];

Upvotes: 158

Related Questions