標籤:
1. 維護前
postgres=# \d+ test Table"public.test" Column | Type | Modifiers| Storage | Stats target | Description--------+-----------------------------+----------------------------------------------------+---------+--------------+------------- id | integer | not null defaultnextval(‘test_id_seq‘::regclass) | plain | | val | timestamp without time zone | default now()| plain | |Indexes: "test_pkey" PRIMARY KEY, btree (id)
2. 建立新的unique index
postgres=# CREATE UNIQUE INDEX CONCURRENTLY ON test USING btree(id);CREATE INDEX
3. 替換主鍵
postgres=# BEGIN;BEGINpostgres=# ALTER TABLE test DROP CONSTRAINT test_pkey;ALTER TABLEpostgres=# ALTER TABLE test ADD CONSTRAINT test_id_idx PRIMARY KEY USINGINDEX test_id_idx;ALTER TABLEpostgres=# COMMIT;COMMIT
4. 維護後
postgres=# \d+ test Table"public.test" Column | Type | Modifiers| Storage | Stats target | Description--------+-----------------------------+----------------------------------------------------+---------+--------------+------------- id | integer | not null defaultnextval(‘test_id_seq‘::regclass) | plain | | val | timestamp without time zone | default now()| plain | |Indexes: "test_id_idx" PRIMARY KEY, btree (id)
這樣的好處是,可以在白天負載低的時候維護主鍵
PostgreSQL主鍵膨脹的使用CONCURRENTLY維護