PRIMARY KEY Constraints in PostgreSQL

Mastering PRIMARY KEY Constraints in PostgreSQL: A Complete Guide


A PRIMARY KEY constraint is one of the most essential elements in relational database management. It uniquely identifies each row in a database table and ensures that the column(s) designated as a PRIMARY KEY contains unique, non-NULL values. This guide will provide you with an in-depth understanding of PRIMARY KEY constraints in PostgreSQL.

What is a PRIMARY KEY?

The PRIMARY KEY constraint ensures each row in a table can be uniquely identified by one or more columns. Each table can have only one PRIMARY KEY, and the column(s) designated as a PRIMARY KEY must contain unique values and cannot contain NULLs.


Here’s the basic syntax for defining a PRIMARY KEY during table creation:

CREATE TABLE table_name (
    column1 data_type PRIMARY KEY,
    column2 data_type,
    column3 data_type,

You can also define a composite PRIMARY KEY using multiple columns:

CREATE TABLE table_name (
    column1 data_type,
    column2 data_type,
    PRIMARY KEY (column1, column2)

Example Using the tv_series Table

Let’s refer to our tv_series table:

CREATE TABLE public.tv_series (
    id serial4 NOT NULL,
    "name" text NOT NULL,
    genre text NOT NULL,
    seasons int4 NULL DEFAULT 1,
    is_running bool NULL DEFAULT true,
    release_year int4 NULL,
    CONSTRAINT tv_series_pkey PRIMARY KEY (id)

In this example, the id column is defined as a PRIMARY KEY, ensuring that each row in the tv_series table is unique based on this column.

Common Errors and Solutions

Error Message:

ERROR: duplicate key value violates unique constraint "tv_series_pkey"


This error occurs when you try to insert a row with a PRIMARY KEY value that already exists in the table.


To resolve this, you can either:

  • Use a unique value for the PRIMARY KEY column.
  • Allow PostgreSQL to auto-generate a unique value if the column type is serial or bigserial.

Error Message:

ERROR: null value in column "id" violates not-null constraint


This error happens when you try to insert a NULL value into a PRIMARY KEY column.


  • Make sure to provide a non-NULL, unique value for the PRIMARY KEY column during insertion.

Best Practices and Tips

  • Use serial, bigserial or uuid data types for auto-generating unique values for PRIMARY KEY columns.
  • Try to keep your PRIMARY KEY as simple as possible. Composite keys can be useful but also add complexity.
  • PRIMARY KEY constraints automatically create a unique index on the PRIMARY KEY column(s), aiding in faster search and retrieval operations.


Understanding the PRIMARY KEY constraint is crucial for anyone working with PostgreSQL or any other relational database. It ensures data integrity by enforcing uniqueness and non-NULL constraints on a column or set of columns. As you continue to work with databases, knowing how to properly set up and manage PRIMARY KEY constraints will be a valuable skill in your toolkit.

Leave a Reply