How to Add a Primary Key in PostgreSQL

Last updated July 25, 2026 · By the SaturnSQL team

Use ALTER TABLE ... ADD PRIMARY KEY (column) on an existing table, or declare GENERATED ALWAYS AS IDENTITY PRIMARY KEY when creating one. The column must be NOT NULL and contain no duplicates.

ALTER TABLE customers ADD PRIMARY KEY (id);

Auto-incrementing key on a new table

CREATE TABLE events (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name TEXT NOT NULL,
  created_at TIMESTAMPTZ DEFAULT now()
);

IDENTITY is the modern replacement for SERIAL: it is SQL-standard and keeps the sequence tied to the column. Adding a primary key builds a unique index, which locks the table; on large tables create a unique index CONCURRENTLY first, then attach it with ADD CONSTRAINT ... PRIMARY KEY USING INDEX.

Run this in SaturnSQL

SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.

Try it free

Related PostgreSQL guides

© 2026 Panda Capital Oy Ab. All rights reserved.