PostgreSQL – Primary Key
Last Updated :
14 Jul, 2024
A primary key is a column or a group of columns used to uniquely identify a row in a table. Technically, a primary key constraint combines a NOT NULL constraint and a UNIQUE constraint. Each table can only have one primary key. When a primary key is added to a table, PostgreSQL automatically creates a unique B-tree index on the column(s) defining the primary key.
Let us get a better understanding of the Primary Key in PostgreSQL from this article.
Syntax
column_name Data-type PRIMARY KEY
PostgreSQL Primary Key Examples
Now let’s look into some examples of the Primary Key in PostgreSQL to better understand the concept.
Example 1: Creating a Table with a Primary Key,
In this example, we will create a table (say, books) and add a column(say, book_id) as the primary key of the table.
PostgreSQL
CREATE TABLE books (
book_id INTEGER PRIMARY KEY,
title TEXT,
price INTEGER
);
INSERT INTO books(book_id, title, price)
VALUES
('101', 'Jobs', '2000'),
('102', 'Geeta', '250'),
('103', 'Ramayana', '354'),
('104', 'Vedas', '268');
SELECT * FROM books;
Output:

Example 2: Adding a Primary Key to an Existing Table
In this example we will be adding PRIMARY key to an existing table. Then, table named ‘vendors' will come up as:
PostgreSQL
CREATE TABLE vendors (name VARCHAR(255));
INSERT INTO vendors (NAME)
VALUES
('Microsoft'),
('IBM'),
('Apple'),
('Samsung');
SELECT * FROM vendors;
Output:

Adding an Auto-Incremented Primary Key
If we want to add a primary key named ‘id' to the ‘vendors' table and make the ‘id' field auto-increment by a single unit, we use the following statement:
ALTER TABLE vendors ADD COLUMN ID SERIAL PRIMARY KEY;
Let’s check the vendors table again using the below command:
SELECT id, name FROM vendors;
Output:

Important Points About PostgreSQL Primary Key
- When you define a primary key, PostgreSQL automatically creates a unique B-tree index on the column(s) used.
- Use
SERIAL or BIGSERIAL for auto-incrementing primary keys. These types automatically generate unique sequential values. - Each table can have only one primary key, but that key can consist of multiple columns (composite key).
- In tables that use inheritance, primary keys are not automatically inherited. You must explicitly define primary keys in each child table.
Please Login to comment...