Serial to identity conversion

From CarlosCaPe/octorato · View interactive version

Serial to identity conversion is an AI agent skill from the GitHub repository CarlosCaPe/octorato. Serial to Identity Column Conversion

How to use this skill

Skill file

Serial to Identity Column Conversion

What

Migrating legacy serial / bigserial columns (which use implicit sequences

via nextval()) to the SQL-standard GENERATED BY DEFAULT AS IDENTITY syntax.

Why

serial is a PostgreSQL shorthand that creates a separate sequence and a

DEFAULT nextval(...) expression. This has drawbacks:

column may leave orphaned sequences

How

Step 1: Check current state

SELECT column_name, column_default, is_identity
FROM information_schema.columns
WHERE table_name = 'FeatureFlags' AND column_name = 'FlagId';
-- If column_default = nextval('...') and is_identity = 'NO', needs conversion

Step 2: Remove the old default

ALTER TABLE feature_flags."FeatureFlags"
    ALTER COLUMN "FlagId" DROP DEFAULT;

Step 3: Drop the orphaned sequence

DROP SEQUENCE IF EXISTS feature_flags."FeatureFlags_FlagId_seq";

Step 4: Add identity

ALTER TABLE feature_flags."FeatureFlags"
    ALTER COLUMN "FlagId"
    ADD GENERATED BY DEFAULT AS IDENTITY;

Step 5: Sync the sequence to max value

-- Critical: set the identity sequence to the current max value
SELECT setval(
    pg_get_serial_sequence('feature_flags."FeatureFlags"', 'FlagId'),
    COALESCE((SELECT MAX("FlagId") FROM feature_flags."FeatureFlags"), 1)
);

GENERATED BY DEFAULT vs GENERATED ALWAYS

| Mode | Behavior | Use When |

|------|----------|----------|

| GENERATED BY DEFAULT | Auto-generates but allows explicit INSERT | App sometimes provides the ID |

| GENERATED ALWAYS | Rejects explicit INSERT (unless OVERRIDING SYSTEM VALUE) | ID must always be auto-generated |

Use BY DEFAULT for backward compatibility with existing app code.

Official PG 16 behavior (sql-createtable.html):

which only has an OWNED BY dependency in pg_depend)

INSERT INTO t OVERRIDING SYSTEM VALUE VALUES (...)

When to Use

Where We Used It

References

-- see Backlog #7 (Replace explicit sequences with IDENTITY)

and "Schema design and data types" section

Gotchas

INSERT will get a duplicate key error


Category: DDL | Origin:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.