136

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 {}

3 Answers 3

165

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[];
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much! I've found another solution too, although don't know which is one more "correct" pwd_history SET DEFAULT '{}'. But as I understand both solutions are resulting the same casting for postgresql (explicit/implicit).
Just as a note for anyone trying to create a default value via SqlAlchemy (for python): you have to use {} for default value in the ORM mapping, e.g. sizes = Column(postgresql.ARRAY(postgresql.TEXT), server_default="{}") and let it do the implicit conversion, as mentioned in @Hett comment above
I've done this with success ALTER TABLE foo ALTER COLUMN bar SET DEFAULT '{}';
I realise the op asked specifically about Pg 9.4, but this might be useful for users of newer versions. Just set the default as the following constant: {}. This would be the DDL: my_array_column text[] DEFAULT '{}'::text[]
79

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 '{}';

Comments

7

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[];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.