A primary key identifies each row uniquely. It carries both UNIQUE and NOT NULL semantics, so the key can never repeat and can never be NULL. PostgreSQL creates a unique index for it automatically, which makes the key both an integrity guarantee and an efficient join key. A table may have only one primary key, but it may span several columns.
The columns forming the key. The table-level form accepts several columns for a composite key; the column-level form applies only to its own column.
Returns:A primary key has no return value of its own. Creating it also builds a unique B-tree index automatically (named `
_pkey`), so lookups and joins on the key columns are index-backed.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
SELECT 'duplicate customer_id' AS step,
(SELECT pg_try('INSERT INTO customers VALUES (1,''Eve'')')) AS result
UNION ALL SELECT 'duplicate (order_id,product_id)',
(SELECT pg_try('INSERT INTO order_items VALUES (1,10,9)'))
UNION ALL SELECT 'order_items rows',
(SELECT count(*)::TEXT FROM order_items)
UNION ALL SELECT 'customers PK name',
(SELECT conname FROM pg_constraint WHERE conrelid='customers'::regclass AND contype='p')
UNION ALL SELECT 'order_items PK name',
(SELECT conname FROM pg_constraint WHERE conrelid='order_items'::regclass AND contype='p')
step | result
---------------------------------+-------------------------------------------------------------------
duplicate customer_id | duplicate key value violates unique constraint "customers_pkey"
duplicate (order_id,product_id) | duplicate key value violates unique constraint "order_items_pkey"
order_items rows | 3
customers PK name | customers_pkey
order_items PK name | order_items_pkey
(5 rows)
QHow is a primary key different from UNIQUE plus NOT NULL?
AFunctionally they are nearly equivalent. The differences are semantic and catalog-level: a table may have only one primary key and PostgreSQL treats it as the table's identity, while UNIQUE constraints may be numerous and imply no identity. A composite key can only be expressed as PRIMARY KEY (a, b).
QMust a primary key be an auto-incrementing integer?
ANo. UUIDs and natural keys such as an email address work as primary keys too. Be aware that random UUIDs as B-tree keys cause write amplification and poor cache locality, so large tables often prefer ordered UUIDs (UUIDv7).
Web-Tutorial Tech Team
A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.