Search code examples
postgresqlprimary-keydefaultuuid

How do I set a default value for a UUID primary key column in Postgres?


I'm using PostgreSQL. I'm trying to create a primary key column taht is a UUID, so I ran this statement

ALTER TABLE my_object_times ADD PRIMARY KEY (id) DEFAULT uuid_generate_v4();

but I get the error

PG::SyntaxError: ERROR:  syntax error at or near "DEFAULT"

What is the proper way to write the above statement (I'm doing alter because I'm changing an existing primary key column)?


Solution

  • If the column id already exists in the table and you want to modify it by making it the primary key and adding a default value, you can do it in 2 steps:

    ALTER TABLE my_object_times ADD PRIMARY KEY (id);
    ALTER TABLE my_object_times ALTER COLUMN id SET DEFAULT uuid_generate_v4();
    

    If the column doesn't exist at all, then you can create it with all the attributes you want, by simply doing:

    ALTER TABLE my_object_times ADD id uuid PRIMARY KEY DEFAULT uuid_generate_v4();
    

    (I cannot test this right now but it should work)