adding-auto-increment-identity-column (US005)#
Automatic fix is not available.
What it does#
Checks adding of auto increment identity column.
Why not?#
Adding an auto increment identity column to an already populated table will have to backfill the newly added column, causing the table to be locked in which no other operations can be performed on the table for the duration of the backfill. This will cause downtime if the table is concurrently being accessed by other clients.
When should you?#
If the table is empty. If the table is not empty but is not being concurrently accessed.
Use instead:#
- Create a new column typed bigint, nullable.
- Create a sequence.
- Set the next value of the sequence to the total number of rows in the table with enough offset.
- Set the default value of the new column to the next value of the sequence.
- Backfill the new column for all existing rows.
- Add a check constraint: CHECK (column IS NOT NULL) NOT VALID.
- Validate the constraint.
- Set the column as NOT NULL
- Drop the constraint.
- Get the last value of the sequence, with enough offset.
- In a single transaction:
- Drop the default on the new column.
- Drop the sequence created in step 2.
- Add GENERATED ALWAYS AS IDENTITY constraint instead, specifying the start option as the value from step 10.