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

PostgreSQL – Primary Key

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

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
For developers working in corporate environments, admin privileges to install software might be restricted. But if we’re looking to explore PostgreSQL on our own, here’s a step-by-step guide on installing PostgreSQL without admin rights on a Windows system. Follow this guide to set up PostgreSQL manually, create a database, and verify the installat
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
Foreign keys play a crucial role in relational databases by establishing relationships between tables and safeguarding data integrity. In this PostgreSQL foreign key tutorial, we'll cover how foreign keys work, their importance and how to create them. We will also learn about foreign key constraints and their role in ensuring data consistency. By t
5 min read
Foreign Key with a Null Value in PostgreSQL
PostgreSQL supports foreign keys to ensure referential integrity between tables. Nullable foreign keys add flexibility by allowing child table rows to either reference a parent table or have a NULL value, meaning no association. While this is useful in certain cases, managing nullable foreign keys carefully is important to maintain data integrity.
6 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
PostgreSQL - Loading a Database
In this article we will look into the process of loading a PostgreSQL database into the PostgreSQL database server. Before moving forward we just need to make sure of two things: PostgreSQL database server is installed on your system. A sample database. For the purpose of this article, we will be using a sample database which is DVD rental database
3 min read
PostgreSQL - LIKE operator
The PostgreSQL LIKE operator is used query data using pattern matching techniques. Its result include strings that are case-sensitive and follow the mentioned pattern. It is important to know that PostgreSQL provides with 2 special wildcard characters for the purpose of patterns matching as below: Percent ( %) for matching any sequence of character
2 min read
Install PostgreSQL on Linux
This is a step-by-step guide to install PostgreSQL on a Linux machine. By default, PostgreSQL is available in all Ubuntu versions as PostgreSql "Snapshot". However other versions of the same can be downloaded through the PostgreSQL apt repository. We will be installing PostgreSQL version 11.3 on Ubuntu in this article. There are three crucial steps
2 min read
PostgreSQL - Size of tablespace
In this article, we will look into the function that is used to get the size of the PostgreSQL database tablespace. The pg_tablespace_size() function is used to get the size of a tablespace of a table. This function accepts a tablespace name and returns the size in bytes. Syntax: select pg_tablespace_size('tablespace_name'); Example 1: Here we will
2 min read
PostgreSQL - Removing Temporary Table
In PostgreSQL, one can drop a temporary table by the use of the DROP TABLE statement. Syntax: DROP TABLE temp_table_name; Unlike the CREATE TABLE statement, the DROP TABLE statement does not have the TEMP or TEMPORARY keyword created specifically for temporary tables. To demonstrate the process of dropping a temporary table let's first create one b
2 min read
PostgreSQL - Block Structure
PL/pgSQL is a block-structured language, therefore, a PL/pgSQL function or store procedure is organized into blocks. Syntax: [ <<label>> ] [ DECLARE declarations ] BEGIN statements; ... END [ label ]; Let's analyze the above syntax: Each block has two sections: declaration and body. The declaration section is optional while the body sec
4 min read
Introduction to PostgreSQL PL/pgSQL
In this, we will discuss the overview of PostgreSQL PL/pgSQL and will also cover the CRUD(CREATE, READ, UPDATE, DELETE) operations with the help of the example of each operation and finally will discuss the advantages and disadvantages of PostgreSQL PL/pgSQL. Let's discuss it one by one.PostgreSQL :It is a powerful, open-source object-relational da
4 min read
PostgreSQL - Select Into
In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword. The select into statement will assign the data returned by the select clause to the variable. Besides selecting
2 min read
PostgreSQL - Insert Data Into a Table using Python
In this article we will look into the process of inserting data into a PostgreSQL Table using Python. To do so follow the below steps: Step 1: Connect to the PostgreSQL database using the connect() method of psycopg2 module.conn = psycopg2.connect(dsn) Step 2: Create a new cursor object by making a call to the cursor() methodcur = conn.cursor() Ste
2 min read
How to use PostgreSQL Database in Django?
This article revolves around how can you change your default Django SQLite-server to PostgreSQL. PostgreSQL and SQLite are the most widely used RDBMS relational database management systems. They are both open-source and free. There are some major differences that you should be consider when you are choosing a database for your applications. Also ch
2 min read
PostgreSQL - SQL Optimization
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. You can download th
5 min read
PostgreSQL CRUD Operations using Java
CRUD (Create, Read, Update, Delete) operations are the basic fundamentals and backbone of any SQL database system. CRUD is frequently used in database and database design cases. It simplifies security control by meeting a variety of access criteria. The CRUD acronym identifies all of the major functions that are inherent to relational databases and
8 min read
How To Connect and run SQL queries to a PostgreSQL database from Python
This article focus on connecting to a PostgreSQL database from Python. Installation:Install PostgreSQL, If you haven't installed it.We need to install the psycopg2 library to connect to a PostgreSQL database. Open the command prompt and run the below command to install psycopg2pip3 install psycopg2Creating a Database You can create a Database in 2
2 min read
Spring Boot Integration With PostgreSQL as a Maven Project
PostgreSQL is a user-friendly versatile RDBMS. This article lets us see how to integrate Spring Data JPA with PostgreSQL. There are some conventions to be followed while using PostgreSQL. We will cover that also. Working with PostgreSQL We can easily create databases and tables in that. The below screenshot will help with how to connect to PostgreS
3 min read
Run PostgreSQL on Docker and Setting Up pgAdmin
PostgreSQL, an effective tool, is a free­-to-use relational database management system. Docker can quickly construct and orche­strate its instances without bothering about the complexity of setup or depe­ndencies. This step-by-step simple guide will show you how to get Postgre­SQL on Docker, and then, use the pgAdmin extension to look at the databa
7 min read
How to Extract Date From a TimeStamp in PostgreSQL
PostgreSQL is a powerful open-source relational database management system (RDBMS). PostgreSQL is well-known for its feature-rich capabilities, standardization, and adaptability. It supports a variety of data types, complex SQL queries, and ACID properties. PostgreSQL offers scalability and durability, making it a popular option for both small proj
4 min read
How to Boost Speed of Queries in Stored Procedures in PostgreSQL?
Usually, when we have large procedures in PostgreSQL we find them taking a lot of time (for eg. a task that would take normally 5 mins would go for more than 30 mins). The Major factor here which causes is that when we have more updates and insert statements in our procedure and the amount of data inserted or updated is huge then Postgres is not ab
3 min read
How to Update Top 100 Records in PostgreSQL?
PostgreSQL is one of the most advanced general-purpose object-relational database management systems and is open-source. Being an open-source software, its source code is available under the open-sourcePostgreSQL license, a liberal open-source license. Anyone with the right skills is free to use, modify, and distribute PostgreSQL in any form. As it
5 min read
How to Insert Text With Single Quotes in PostgreSQL
SQL stands for structured query language and is used to query databases for analytical needs. While using arithmetic queries, some results require strings to help them understand better. Strings can be formed by enclosing text in quotes. However in a case when quotes are themselves required in a string, then we need to escape them. In this article,
4 min read
How to Insert Multiple Rows to a Table in PostgreSQL?
Inserting multiple rows into a table in PostgreSQL is a common operation that may enhance efficiency when managing large datasets. By executing a single SQL query, more than one row is inserted simultaneously, which reduces the overload of multiple individual inserts. This method not only helps in the insertion process but also enhances the databas
4 min read
three90RightbarBannerImg