I have to reconfigure one table with existing data so need advice/example how to do that.
My favourite example table:
DROP TABLE IF EXISTS kalksad1;
CREATE TABLE kalksad1(
kalk_id int PRIMARY KEY,
brkalk integer,
brred integer,
description text
);
INSERT INTO kalksad1 VALUES
(12, 2, 5, 'text index 12 doc 2 row 5'),
(26, 2, 1, 'text index 26 doc 2 row 1'),
(30, 2, 2, 'text index 30 doc 2 row 2'),
(32, 4, 1, 'text index 32 doc 4 row 1'),
(36, 1, 1, 'text index 36 doc 1 row 1'),
(37, 1, 2, 'text index 37 doc 1 row 2'),
(38, 5, 1, 'text index 38 doc 5 row 1'),
(39, 5, 2, 'text index 39 doc 5 row 2'),
(42, 2, 3, 'text index 42 doc 2 row 3'),
(43, 2, 4, 'text index 43 doc 2 row 4'),
(46, 3, 1, 'text index 46 doc 3 row 1'),
(47, 3, 2, 'text index 47 doc 3 row 2');
By simple words I need few steps.
1) Add one new column 'kalk_br' of 'int' type. (I know to do that),
2) Copy contents of all cells 'kalk_id' to 'kalk_br'. (I don't know to do that),
3) Change column type for 'kalk_id' from 'int' to 'serial'. (I don't know to do that since 'kalk_id' is PRIMARY KEY).
EDIT by wildplasser's advice: 4) set the current value for the serial to MAX(kalk_id)
Is this possible to do and how? If not, please any idea to solve this differently.
EDIT:
This is I came so far:
/*1. rename kalk_id to kalk_br. 2. create a serial column kalk_id. 3. copy contents from kalk_br to kalk_id.*/
ALTER TABLE kalksad1 RENAME COLUMN kalk_id TO kalk_br;
ALTER TABLE kalksad1 ADD COLUMN kalk_id serial;
UPDATE kalksad1 SET kalk_id = kalk_br;
Now remains:
1) Terminate 'kalk_br' to be primary key.
2) Set 'kalk_id' which is now serial to be primary key with highest value updated as current value.