Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql add existing column to composite primary key

Tags:

postgresql

I have a table in postgresql with a composite primary key. The primary key consists of two columns named:

DATETIME, UID

I have a another (non-null) column named ACTION already existing in this table. How do I add ACTION to the composite primary key? Ie: I'd like the resulting primary key of the table to be the triplet:

DATETIME, UID, ACTION
like image 875
David Simic Avatar asked Apr 07 '16 07:04

David Simic


People also ask

How do you update a table with composite primary key?

As the PK moves, the data must be shuffled around disk to keep it in the correct order. Depending on the data set MySQL may have to move many physical rows to do this. The same goes for updating your PK. Changing the PK changes the order on disk and requires many rows to be moved.

How do I add a column to an existing primary key?

ALTER TABLE PrimaryKeyColumnAdd ALTER COLUMN Column2 int NOT NULL ; And step two update the primary key. Don't forget that the primary key is a constraint and constraints cannot be altered only dropped and re-created. PRIMARY KEY (Column1, Column2);

How do I add a column to a composite primary key in Oracle?

Oracle creates an index on the columns of a primary key; therefore, a composite primary key can contain a maximum of 16 columns. To define a composite primary key, you must use the table_constraint syntax rather than the column_constraint syntax.


1 Answers

First drop the primary key constraint. You can get the name of the constraint by typing

\d my_table

and look under indexes for something like:

"my_table_pkey" PRIMARY KEY, btree (datetime, uid)

Drop it by doing:

alter table my_table drop constraint my_table_pkey;

Then create the new composite primary key by doing:

alter table my_table add constraint my_table_pkey primary key (datetime, uid, action);
like image 168
Garrett Avatar answered Sep 21 '22 14:09

Garrett