Skip to content

Primary Key

In one line

A primary key is a column whose value uniquely identifies each row — no two rows share the same primary key value, and it cannot be NULL.

In simple words

A primary key is the unique identifier for each row in a table. No two rows can have the same primary key value, and the value cannot be NULL. This guarantees that you can always find exactly one row by its primary key.

Common choices for primary keys are an auto-incrementing integer (SERIAL in PostgreSQL, AUTO_INCREMENT in MySQL) or a UUID. The auto-incrementing integer is simple and fast; UUIDs are useful when you generate IDs across multiple systems.

A table can have only one primary key, though it can be composed of multiple columns (a composite key). Every table should have a primary key — it is the foundation of relationships and indexing.

Example

sql
CREATE TABLE users (
  id    SERIAL PRIMARY KEY,
  name  TEXT NOT NULL
);
-- 'id' is the primary key: unique, not null, auto-incrementing

The id column is the primary key — PostgreSQL auto-assigns 1, 2, 3, ... for each new row.

Common confusions

  • Confused with: unique key

    The difference: A primary key cannot be NULL and there is only one per table; a unique key can allow NULL (depending on the DBMS) and you can have many per table.

  • Confused with: foreign key

    The difference: A primary key identifies rows in this table; a foreign key references the primary key of another table to create a relationship.

Related terms

Related Resources

Related Lessons

  • Constraints

    Learn about primary keys and other constraints.

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary