Re: How to ALTER a TABLE to change the primary key?

From: Michael Glaesemann <grzm(at)seespotcode(dot)net>
To: Reg Me Please <regmeplease(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: How to ALTER a TABLE to change the primary key?
Date: 2007-10-26 12:34:20
Message-ID: B76E0137-06F0-4F07-B7E4-980F5B8FB638@seespotcode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Oct 26, 2007, at 5:39 , Reg Me Please wrote:

> I'd need to modify the primary key definition in an already
> populated table.
> How can I do it?

Drop the primary key constraint and create a new one. You can do this
inside a transaction.

test=# \d strings
Table "public.strings"
Column | Type | Modifiers
----------+------+-----------
a_string | text | not null
Indexes:
"strings_pkey" PRIMARY KEY, btree (a_string)

test=# begin; alter table strings drop constraint strings_pkey; alter
table strings add constraint new_pkey primary key (a_string); commit;
BEGIN
ALTER TABLE
NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index
"new_pkey" for table "strings"
ALTER TABLE
COMMIT
test=# \d strings;
Table "public.strings"
Column | Type | Modifiers
----------+------+-----------
a_string | text | not null
Indexes:
"new_pkey" PRIMARY KEY, btree (a_string)

Michael Glaesemann
grzm seespotcode net

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Reg Me Please 2007-10-26 12:39:28 Re: INDEX and JOINs
Previous Message Magnus Hagander 2007-10-26 12:29:51 Re: 8.2.3: Server crashes on Windows using Eclipse/Junit