The Wayback Machine - https://web.archive.org/web/20240803185533/https://www.geeksforgeeks.org/postgresql-primary-key/
Open In App

PostgreSQL – Primary Key

Last Updated : 14 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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:

PostgreSQL Primary Key Example

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:


PostgreSQL Primary Key Example

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:

PostgreSQL Primary Key Example

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.

Previous Article
Next Article

Similar Reads

How to Reset the Primary Key Sequence ID in PostgreSQL?
PostgreSQL is a powerful, open-source, object-relational database management system (DBMS) developed by a community of contributors. primary key in PostgreSQL is a unique identifier for each row in a table. It is a column or a combination of columns that ensures the integrity of the data in the table. In this article, we will explore how to Reset t
4 min read
How to Reset PostgreSQL Primary Key Sequence When it Falls Out of Sync?
PostgreSQL, often referred to as Postgres is a powerful, open-source object-relational database management system (ORDBMS). It is widely recognized for its robustness, scalability, and capability to manage large volumes of data. PostgreSQL has been actively developed for over 30 years, with its origins tracing back to the POSTGRES project at the Un
4 min read
PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read
PostgreSQL - Export PostgreSQL Table to CSV file
In this article we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine. For Server-Side Export: Use the below syntax to copy a PostgreSQL table from the server itself: Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER; Note: If you have permissio
2 min read
PostgreSQL - Installing PostgreSQL Without Admin Rights on Windows
If you are a part of a corporation, it is highly unlikely that you have the admin privileges to install any external software. But the curious souls that all software developers are, in this article, we will see the detailed process of installation of PostgreSQL without having administrator rights on our Windows machine. Installation: Follow the be
3 min read
Foreign Key with a Null Value in PostgreSQL
PostgreSQL's support for nullable foreign key columns provides flexibility in cases where child table rows may not reference specific parent table rows. However, managing these nullable foreign keys requires attention to maintain data integrity. Explore the methods and implications of implementing nullable foreign keys in PostgreSQL. When using nul
5 min read
Foreign Key Indexing and Performance in PostgreSQL
As the world of databases is always changing, PostgreSQL is one of the autonomous options because of its dependability, capability to handle huge amounts of data, and fast performance. Effective indexing, especially for foreign keys, is an important key for enhancing the speed of PostgreSQL. Appropriate indexes for foreign keys can greatly speed up
4 min read
PostgreSQL - Foreign Key
A Foreign Key is a column or a group of columns used to uniquely identify a row in a different table. The table containing the foreign key is called the referencing table or child table, while the table that the foreign key references is known as the referenced table or parent table. A table can have multiple Foreign Keys, depending on its relation
7 min read
PostgreSQL - Creating Updatable Views Using WITH CHECK OPTION Clause
PostgreSQL is the most advanced general purpose open source database in the world. pgAdmin is the most popular management tool or development platform for PostgreSQL. It is also an open source development platform. It can be used in any Operating Systems and can be run either as a desktop application or as a web in your browser. In this article, we
4 min read
What is PostgreSQL - Introduction
This is an introductory article for the PostgreSQL database management system. In this we will look into the features of PostgreSQL and why it stands out among other relational database management systems. Brief History of PostgreSQL: PostgreSQL also known as Postgres, was developed by Michael Stonebraker of the University of California, Berkley. I
2 min read
three90RightbarBannerImg