# Postgres identity columns: GENERATED ALWAYS vs BY DEFAULT, and moving off serial

What PostgreSQL identity columns change compared with serial: GENERATED ALWAYS vs BY DEFAULT, OVERRIDING SYSTEM VALUE, sequence permissions, changing the column type, CREATE TABLE LIKE, COPY, and partitioned tables in Postgres 17. Plus a procedure that converts serial columns to identity in place in milliseconds, without rewriting the table. Every statement replayed on Postgres 17.11.

**`serial` looks like a column type, but it isn't one. It is shorthand for three objects: an `integer` column, a separate sequence, and a default that calls `nextval()`. Postgres 10 added the SQL-standard replacement, `GENERATED ... AS IDENTITY`, where the column owns its sequence. Most tutorials stop at "use identity, it's the standard". This post shows what actually changes: which inserts and updates each form accepts, the permission error that `serial` causes and identity doesn't, the type change that leaves a `serial` column stuck at 2,147,483,647, the copy of a table that silently shares its parent's sequence, and what Postgres 17 fixed for partitioned tables. It ends with a procedure that converts existing `serial` columns to identity in place. On a million-row table it took about a millisecond and didn't rewrite the table. Every output below comes from scripted replays on PostgreSQL 17.11, the major version Relyt One runs, with 16.16 for one comparison.**

## The short version

- **New tables: `id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY`.** `ALWAYS` rejects explicit IDs unless you write `OVERRIDING SYSTEM VALUE`, so stray IDs from app code fail loudly.
- **`BY DEFAULT` behaves like `serial`.** An explicit ID is accepted, and the sequence doesn't move, so the next generated ID can collide with it. Use it when something legitimately supplies IDs, such as a migration or a sync job.
- **Identity fixes three `serial` problems** you'd otherwise hit in production: the extra `GRANT` on the sequence, a sequence stuck at `integer` after you widen the column to `bigint`, and table copies that share one sequence.
- **Identity doesn't fix gaps or bulk loads.** Rollbacks still burn numbers, and `COPY` writes your IDs even into a `GENERATED ALWAYS` column without moving the sequence. After a load, set the sequence yourself.
- **Converting from `serial` is a metadata change.** Drop the default, drop the old sequence, add identity starting at the next free number. It takes an `ACCESS EXCLUSIVE` lock for milliseconds and doesn't rewrite the table.

## What serial really creates

Create a table with `serial` and look at it in `psql`:

```sql
CREATE TABLE orders_serial (id serial PRIMARY KEY, note text);
\d orders_serial
```

```text
                            Table "public.orders_serial"
 Column |  Type   | Collation | Nullable |                  Default
--------+---------+-----------+----------+-------------------------------------------
 id     | integer |           | not null | nextval('orders_serial_id_seq'::regclass)
 note   | text    |           |          |
```

The column is a plain `integer` with a default. The [Postgres manual](https://www.postgresql.org/docs/17/datatype-numeric.html#DATATYPE-SERIAL) spells out the expansion: create a sequence, create the column with `DEFAULT nextval(...)` and `NOT NULL`, then `ALTER SEQUENCE ... OWNED BY` the column so the sequence is dropped with it. That's all the link there is. The default is an ordinary expression that can be dropped or changed by accident, and the sequence is an ordinary object with its own permissions.

An identity column looks different:

```sql
CREATE TABLE orders (
  id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  note text
);
\d orders
```

```text
                         Table "public.orders"
 Column |  Type  | Collation | Nullable |           Default
--------+--------+-----------+----------+------------------------------
 id     | bigint |           | not null | generated always as identity
 note   | text   |           |          |
```

There's still a sequence behind it (`pg_get_serial_sequence('orders', 'id')` returns `public.orders_id_seq`), but now it's part of the column. You can't drop it, and you can't remove the default by accident:

```sql
ALTER TABLE orders ALTER COLUMN id DROP DEFAULT;
DROP SEQUENCE orders_id_seq;
```

```text
ERROR:  column "id" of relation "orders" is an identity column
HINT:  Use ALTER TABLE ... ALTER COLUMN ... DROP IDENTITY instead.
ERROR:  cannot drop sequence orders_id_seq because column id of table orders requires it
HINT:  You can drop column id of table orders instead.
```

![Two diagrams side by side. Left: a serial column whose DEFAULT nextval() points to a separate sequence that needs its own GRANT. Right: an identity column whose sequence is internal to the column.](/blog/assets/924185e65993b291.svg)

## GENERATED ALWAYS vs BY DEFAULT

The two forms differ only in what happens when a statement supplies its own value. The [`CREATE TABLE` reference](https://www.postgresql.org/docs/17/sql-createtable.html) defines it: with `ALWAYS`, an insert's value is accepted only with `OVERRIDING SYSTEM VALUE`; with `BY DEFAULT`, the user's value takes precedence.

Here's `ALWAYS` in practice:

```sql
INSERT INTO orders (note) VALUES ('a') RETURNING id;           -- 1
INSERT INTO orders (id, note) VALUES (100, 'explicit');
```

```text
ERROR:  cannot insert a non-DEFAULT value into column "id"
DETAIL:  Column "id" is an identity column defined as GENERATED ALWAYS.
HINT:  Use OVERRIDING SYSTEM VALUE to override.
```

The `DEFAULT` keyword still works, which matters for ORMs that list every column:

```sql
INSERT INTO orders (id, note) VALUES (DEFAULT, 'default kw') RETURNING id;   -- 2
```

When you really do need to write an ID, for example while restoring a row, say so:

```sql
INSERT INTO orders (id, note) OVERRIDING SYSTEM VALUE
VALUES (100, 'override') RETURNING id;                          -- 100
```

`ALWAYS` also protects updates. There's no `OVERRIDING` clause for `UPDATE`, so the only value you can set is `DEFAULT`, which takes a fresh number:

```sql
UPDATE orders SET id = 5 WHERE id = 1;
```

```text
ERROR:  column "id" can only be updated to DEFAULT
DETAIL:  Column "id" is an identity column defined as GENERATED ALWAYS.
```

```sql
UPDATE orders SET id = DEFAULT WHERE id = 1 RETURNING id;        -- 3
```

Now the trap with `BY DEFAULT`. It accepts explicit values, but nothing tells the sequence about them:

```sql
CREATE TABLE orders_bd (
  id   bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  note text
);
INSERT INTO orders_bd (id, note) VALUES (1, 'explicit');   -- accepted
INSERT INTO orders_bd (note) VALUES ('generated');
```

```text
ERROR:  duplicate key value violates unique constraint "orders_bd_pkey"
DETAIL:  Key (id)=(1) already exists.
```

The sequence handed out 1, which was already taken. This is the same failure people hit with `serial` after an import, and the same fix applies. We covered it in detail, including a query that resets every sequence at once, in [why Postgres IDs skip numbers and how to fix "duplicate key" errors](/blog/postgres-sequence-gaps-duplicate-key).

The opposite clause, `OVERRIDING USER VALUE`, ignores the supplied ID and generates one. It works on both kinds of identity column, and it's handy when you copy rows between tables with `INSERT ... SELECT *` and want the target to number them itself:

```sql
INSERT INTO orders_bd (id, note) OVERRIDING USER VALUE
VALUES (999, 'ignored id') RETURNING id;                    -- 2, not 999
```

**Which one to pick.** Use `ALWAYS` unless something outside the database owns the IDs. A wrong explicit ID then fails on the insert that wrote it, not later on an unrelated insert that collides with it. Use `BY DEFAULT` when you migrate from `serial` and existing code still writes IDs, then switch to `ALWAYS` once it doesn't. Switching is a single statement: `ALTER TABLE orders ALTER COLUMN id SET GENERATED ALWAYS`.

## Three serial problems identity removes

### 1. A second GRANT for the sequence

Give an application role `INSERT` on both tables and try to insert:

```sql
CREATE ROLE app_writer LOGIN;
GRANT INSERT, SELECT ON orders, orders_serial TO app_writer;
SET ROLE app_writer;

INSERT INTO orders_serial (note) VALUES ('as app_writer');
INSERT INTO orders (note) VALUES ('as app_writer') RETURNING id;
```

```text
ERROR:  permission denied for sequence orders_serial_id_seq
 id
----
  4
```

The `serial` table fails because the default calls `nextval()` on a separate object, and the role has no `USAGE` on it. Every `serial` table needs a matching `GRANT USAGE ON SEQUENCE`, or a one-time `ALTER DEFAULT PRIVILEGES ... GRANT USAGE ON SEQUENCES` that covers sequences created later by the same role. It's easy to forget either one, and you find out from the first insert in production. The identity insert works with table privileges alone.

### 2. Widening the column leaves the sequence behind

Since Postgres 10, `serial` creates its sequence `AS integer`. Run out of room, widen the column to `bigint`, and look at the sequences:

```sql
CREATE TABLE t_serial (id serial PRIMARY KEY);
CREATE TABLE t_ident  (id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY);

ALTER TABLE t_serial ALTER COLUMN id TYPE bigint;
ALTER TABLE t_ident  ALTER COLUMN id TYPE bigint;

SELECT seqrelid::regclass AS seq, seqtypid::regtype AS type, seqmax
FROM pg_sequence
WHERE seqrelid IN ('t_serial_id_seq'::regclass, 't_ident_id_seq'::regclass);
```

```text
       seq       |  type   |       seqmax
-----------------+---------+---------------------
 t_serial_id_seq | integer |          2147483647
 t_ident_id_seq  | bigint  | 9223372036854775807
```

The identity sequence followed the column. The `serial` one didn't, so after the slow part of the migration (changing a column's type rewrites the table), inserts still stop at the old limit:

```text
ERROR:  nextval: reached maximum value of sequence "t_serial_id_seq" (2147483647)
```

The fix is `ALTER SEQUENCE t_serial_id_seq AS bigint`, as long as you remember it. With identity there's nothing to remember.

### 3. Copies of a table share one sequence

`CREATE TABLE ... (LIKE ... INCLUDING ALL)` is a common way to make a staging or archive table. With `serial`, the copied default still points at the original's sequence:

```sql
CREATE TABLE copy_serial (LIKE orders_serial INCLUDING ALL);
\d copy_serial
```

```text
 Column |  Type   | Collation | Nullable |                  Default
--------+---------+-----------+----------+-------------------------------------------
 id     | integer |           | not null | nextval('orders_serial_id_seq'::regclass)
```

Both tables now draw from one sequence, and the original's sequence can't be dropped while the copy depends on it. The same copy of an identity table gets its own sequence: the first insert into `copy_ident` returns `1`.

## What identity doesn't change

- **Gaps.** An identity column is still backed by a sequence, and sequences don't roll back. Failed inserts, `ON CONFLICT` and crashes leave holes exactly as with `serial`. The [sequence gaps post](/blog/postgres-sequence-gaps-duplicate-key) reproduces each kind.
- **`COPY` writes your IDs, even into `GENERATED ALWAYS`.** The manual says so in a parenthesis: "In the COPY command, user-specified values are always used regardless of this setting." We copied a row with `id = 500` into `orders`; it was accepted, and the next generated ID was `5`. After a bulk load, move the sequence past the loaded data with `setval()`.
- **`TRUNCATE ... RESTART IDENTITY`** resets both kinds, and `pg_get_serial_sequence()` finds the sequence for both, so scripts that use it keep working.

To manage the sequence of an identity column, use `ALTER TABLE` rather than `ALTER SEQUENCE`:

```sql
ALTER TABLE orders ALTER COLUMN id RESTART WITH 1000;
ALTER TABLE orders ALTER COLUMN id SET INCREMENT BY 10;
ALTER TABLE orders ALTER COLUMN id SET GENERATED BY DEFAULT;
```

To check a column, `information_schema.columns` reports `is_identity = YES` and `identity_generation` (`ALWAYS` or `BY DEFAULT`).

## Partitioned tables: fixed in Postgres 17

[Postgres 17's release notes](https://www.postgresql.org/docs/17/release-17.html) include "Allow partitioned tables to have identity columns". Postgres 16 already accepts the definition on the parent, and inserts through the parent work. What 17 adds is that the partitions share the identity. We ran the same script on 16.16 and 17.11:

```sql
CREATE TABLE events (
  id         bigint GENERATED ALWAYS AS IDENTITY,
  created_at date NOT NULL,
  PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_11 PARTITION OF events
  FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');

INSERT INTO events (created_at) VALUES ('2026-11-05');          -- both versions: id 1
INSERT INTO events_2026_11 (created_at) VALUES ('2026-11-06');  -- straight into a partition
```

On 17.11 the second insert gets the next ID from the parent's sequence. On 16.16 it fails, because the partition doesn't have the identity:

```text
ERROR:  null value in column "id" of relation "events_2026_11" violates not-null constraint
```

If anything writes straight into partitions, such as a loader that targets the current month's table, you need 17 for identity. Relyt One runs 17.

## Converting serial columns to identity in place

Because `serial` is just a default and a sequence, converting it doesn't touch the data. The steps are: lock the table, work out the next number the old sequence would hand out, drop the default and the sequence, and add identity starting at that number. Here it is as a procedure:

```sql
CREATE PROCEDURE serial_to_identity(tbl regclass, col name)
LANGUAGE plpgsql AS $$
DECLARE
  seq      regclass := pg_get_serial_sequence(tbl::text, col)::regclass;
  next_val bigint;
BEGIN
  IF seq IS NULL THEN
    RAISE EXCEPTION 'column %.% is not backed by an owned sequence', tbl, col;
  END IF;

  -- block writers so nobody takes a number while we switch
  EXECUTE format('LOCK TABLE %s IN ACCESS EXCLUSIVE MODE', tbl);

  -- the number the old sequence would hand out next, but never below max(id) + 1
  EXECUTE format('SELECT CASE WHEN is_called THEN last_value + 1 ELSE last_value END FROM %s', seq)
    INTO next_val;
  EXECUTE format('SELECT greatest($1, coalesce(max(%I), 0) + 1) FROM %s', col, tbl)
    USING next_val INTO next_val;

  EXECUTE format('ALTER TABLE %s ALTER COLUMN %I DROP DEFAULT', tbl, col);
  EXECUTE format('DROP SEQUENCE %s', seq);
  EXECUTE format('ALTER TABLE %s ALTER COLUMN %I ADD GENERATED BY DEFAULT AS IDENTITY (START WITH %s)',
                 tbl, col, next_val);
  RAISE NOTICE '%.%: identity, next value %', tbl, col, next_val;
END $$;
```

A few choices in there are deliberate:

- **It keeps the old sequence's position, not just `max(id) + 1`.** Our test table had a million rows, but the sequence had already handed out 1,000,005 and the last 10 rows were deleted. Restarting at `max(id) + 1` would reuse IDs that may still exist in logs, caches or other systems. The procedure started at 1,000,006. (It assumes the default increment of 1.)
- **It uses `BY DEFAULT`,** so code that still writes explicit IDs keeps working. Tighten to `ALWAYS` later.
- **Usually, the new sequence gets the old name.** Identity picks `<table>_<column>_seq`, which is free again after the drop. If the table and column were never renamed, that's the old name, and code that calls `nextval('legacy_id_seq')` directly keeps working. Grants on the old sequence are dropped with it, so that code needs `GRANT USAGE ON SEQUENCE` again. Other sequence options (`CACHE`, `MAXVALUE`, `CYCLE`) aren't carried over either.

Run it on one table inside a transaction:

```sql
BEGIN;
CALL serial_to_identity('legacy', 'id');
COMMIT;
```

```text
NOTICE:  legacy.id: identity, next value 1000006
CALL
Time: 1.079 ms
```

Three more runs took between 1.0 and 4.4 ms. The table's file node was the same before and after (`pg_relation_filenode('legacy')`), so nothing was rewritten. The only work proportional to the table is `max(id)`, which is instant with an index on the column (the primary key here). Without one, it's a full scan while the lock is held: 23 ms on the same million rows, and more on bigger tables. The lock is `ACCESS EXCLUSIVE` and lasts until `COMMIT`, which conflicts with everything, including reads. Keep the transaction short and set a `lock_timeout` so the `LOCK TABLE` gives up instead of queueing behind a long-running query; our [post on migration locks](/blog/postgres-migration-locks) explains why that queue blocks everyone else too. An `integer` column stays `integer`; converting it doesn't widen it.

To convert every `serial` column, find them through `pg_depend`. `serial` marks its sequence with an auto dependency (`deptype = 'a'`), while identity uses an internal one (`'i'`), so identity columns don't show up. The join on `pg_attrdef` keeps only columns whose default is exactly `nextval()` of their own sequence, which skips hand-written defaults such as `nextval(...) * 10` that the conversion would silently replace:

```sql
SELECT format('CALL serial_to_identity(%L, %L)', a.attrelid::regclass, a.attname)
FROM pg_depend d
JOIN pg_class s     ON s.oid = d.objid AND s.relkind = 'S'
JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid
JOIN pg_attrdef ad  ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
WHERE d.classid    = 'pg_class'::regclass
  AND d.refclassid = 'pg_class'::regclass
  AND d.deptype    = 'a'
  AND pg_get_expr(ad.adbin, ad.adrelid) = format('nextval(%L::regclass)', s.oid::regclass)
\gexec
```

`\gexec` is a `psql` command: it runs each row of the result as a statement. In psql's default autocommit mode each `CALL` commits on its own, so a table that fails stays as it was and the rest go ahead. A `bigserial` column converted this way keeps its `bigint` sequence. Tables that use old-style inheritance (`INHERITS`) need manual work: the children inherit the parent's default, not its identity, so convert them by hand. Partitioned tables on 17 convert fine.

> **Shared sequences stop the conversion**
>
> If another table's default still points at the sequence (the `LIKE ... INCLUDING ALL` case above), `DROP SEQUENCE` fails with "cannot drop sequence ... because other objects depend on it" and the procedure aborts without changing anything. Find those columns first: they have a `nextval(...)` default, but `pg_get_serial_sequence()` returns `NULL` for them. Give them their own identity, or decide which table keeps the old numbering.

## Try the conversion on a branch first

The conversion takes milliseconds, but it touches every table that has a `serial` column, and the failures are the shared-sequence and lock cases above. Find them before they reach production. On Relyt One, a branch shares its parent's data copy-on-write and has its own compute. Create a branch, run the `\gexec` query there, insert a row into each converted table, and run your application's tests against it. Writes on a branch don't touch its parent. If something fails, delete the branch and start over.

Relyt One runs PostgreSQL 17, so partitioned tables get identity columns too. Nothing in this post needs an extension. For a one-screen definition, see the [identity column entry in our Postgres glossary](/glossary/identity-column).

[Start for free](/auth/signin?ref=blog-postgres-identity-columns)
