POSTGRESQL

What Is a PostgreSQL Primary Key?

intro

PostgreSQL Primary key: What is it, how does it work, and why is it necessary for your database operations? Learn more here.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT
PostgreSQL logo POSTGRESQL
THE POSTGRESQL DATABASE

As the core part and parcel of database design, PostgreSQL primary key constraints ensure that each record in a table is uniquely identified and can be easily accessed. This article seeks to educate readers on the primary key in PostgreSQL - what it is about, the ins and outs, and how to better implement and utilize this key.

What Is a Key in a Database?

Keys are unique identifiers used to establish relationships between tables and ensure data integrity. They are essential for identifying and retrieving specific records within a table. The most common types of keys include primary keys and foreign keys. But in this blog, we’re going to focus on PostgreSQL primary keys.

Understanding What a PostgreSQL Primary Key Is

In PostgreSQL, a primary key is a constraint involving one or more columns that is used to specifically identify a row in a given table. In a production environment, it is always recommended to add a primary key to each table when dealing with a database.

When you add a primary key to a table in PostgreSQL, the database automatically creates a unique B-tree index on the specified column(s) to ensure that all values in the primary key column(s) are unique. This mechanism also allows for efficient data retrieval.

In theory, a primary key constraint is the result of combining a UNIQUE constraint with a NOT NULL constraint (i.e., UNIQUE constraint + NOT NULL constraint = Primary Key). Learn more about constraints in our guide on PostgreSQL data integrity.

A PostgreSQL primary key has several characteristics. A few of these characteristics are as follows:

  1. Uniquely identifies each row: The value of the primary key must be unique for each row in the table, ensuring that every record can be individually identified.
  2. Cannot contain NULL values: Primary key columns are not allowed to have NULL values, as this would violate the uniqueness requirement.
  3. Automatically indexed: PostgreSQL automatically creates an index on the primary key column(s), enabling fast data retrieval and filtering based on the primary key.

PostgreSQL supports several data types for primary keys, including:

  • Serial data type: An auto-incrementing integer, which is a common choice for primary keys.
  • UUID data type: A universally unique identifier, often used when the order of the primary key values is not important.
  • Composite primary keys: A combination of multiple columns that together uniquely identify each row.

It is important to note that a table can have a primary key or none but cannot have more than one as PostgreSQL does not allow a table to have more than one primary key.

PostgreSQL Primary Key: Operating Syntax

You typically define a primary key when creating a table like this:

Copy
        
1 CREATE TABLE employees ( 2 column1 datatype SERIAL PRIMARY KEY, 3 column2 datatype, 4 .... 5 );
Defining a primary key
Defining a primary key

To add a primary key to an already existing table, use the ALTER TABLE statement as shown here:

Copy
        
1 ALTER TABLE table_name 2 ADD PRIMARY KEY (column_1, column_2, ...);
Adding a primary key to an already existing table
Adding a primary key to an already existing table

When you’re performing this action, and you fail to define the primary key, PostgreSQL will assign a name to the primary key constraint by default using its conventional format:

Copy
        
1 tablename_pkey

Use Cases of Primary Keys in PostgreSQL

Time to explore some primary key use cases in PostgreSQL! The queries below will be executed in DbVisualizer, the world’s leading database client with the highest user satisfaction. In addition to being able to connect to several DBMSs, it offers great features and full support for all database PostgreSQL capabilities. Try DbVisualizer out now!

Example #1 — Adding A Serial Primary Key in a Patient Registration Table

Imagine you have a table for patient registration, where you want each patient to be assigned a unique ID:

Copy
        
1 CREATE TABLE patients ( 2 patient_id SERIAL PRIMARY KEY, 3 username VARCHAR(50) NOT NULL, 4 email VARCHAR(50) NOT NULL, 5 registration_date DATE NOT NULL 6 ); 7 8 INSERT INTO patients (username, email, registration_date) 9 VALUES ('Leslie', 'leslie@hotmail.com', '2024-06-23'), 10 ('Antoine', 'a11@yahoo.com', '2024-05-20'); 11 12 SELECT * FROM patients;
Patient table registration query
Patient table registration query

In the query above, we

  • Create the patients table with the patient_id as the primary key.
  • Define the patient_id column with the SERIAL data type. This will tell PostgreSQL to generate a unique integer (i.e., 1, 2, 3, etc.) when a new row is inserted into the table without providing the value for the patient_id column.

Why are we doing this? It’s very simple - to ensure the value in the patient_id is unique for every row in our table.

Example #2 — Adding A Primary Key To An Existing Table

For example, let’s assume you’ve already created a table for a db you’re working on and after creating it, you quickly remembered that you’ve made a mistake by not assigning a primary key constraint to one of your columns. Fret less—it doesn’t call for alarm at all!

Copy
        
1 CREATE TABLE accessories ( 2 accessory_id INT, 3 name VARCHAR(255) NOT NULL, 4 description TEXT, 5 price DEC(10, 2) NOT NULL 6 );
Creating our table in DbVisualizer
Creating our table in DbVisualizer

Assuming the query above creates the table, we could simply add the primary key to our column by doing this:

Copy
        
1 ALTER TABLE accessories 2 ADD PRIMARY KEY (accessory_id);
Adding a primary key to our column
Adding a primary key to our column

Example #3 — Composite Primary Key In a Many-to-Many Relationship

Primary keys can also be composed of multiple columns, known as a composite primary key. More often than not, it is used in many-to-many relationships, where each row in a table represents a unique combination of the related entities. Here's an example of a student-course enrollment table with a composite primary key:

Copy
        
1 CREATE TABLE student_course_enrollment ( 2 student_id INTEGER NOT NULL, 3 course_id INTEGER NOT NULL, 4 enrollment_date DATE NOT NULL, 5 PRIMARY KEY (student_id, course_id) 6 ); 7 8 INSERT INTO student_course_enrollment (student_id, course_id, enrollment_date) 9 VALUES (1, 101, '2024-06-23'), 10 (1, 102, '2024-06-15'), 11 (2, 101, '2024-06-01'), 12 (2, 103, '2024-06-08'); 13 14 SELECT * FROM student_course_enrollment;
Defining a composite primary key in DbVisualizer
Defining a composite primary key in DbVisualizer

In this example, the primary key is composed of the student_id and course_id columns, ensuring that each unique combination of student and course is represented by a single row in the table.

Other Actions That Can Be Performed On a PostgreSQL Primary Key

This section will highlight some of the actions that can be performed on a primary key in PostgreSQL.

1 — Dropping a Primary Key In PostgreSQL

Primary keys can be dropped using the ALTER TABLE statement with the DROP CONSTRAINT clause. For example:

Copy
        
1 ALTER TABLE my_table 2 DROP CONSTRAINT my_table_pkey;

This will remove the primary key constraint from our table, however, it's important to note that dropping a primary key can have significant consequences, as it can lead to data trust issues and affect the dependent objects (such as foreign key constraints or indexes) that rely on our primary key.

2 — Renaming a Primary Key

The primary key constraint can be renamed using the ALTER TABLE statement with the RENAME CONSTRAINT clause:

Copy
        
1 ALTER TABLE my_table 2 RENAME CONSTRAINT my_table_pkey TO new_pkey_name;

3 — Modifying a Primary Key

In some cases, you may need to modify the columns that make up the primary key. This can be done by first dropping the existing primary key and then adding a new one with the desired columns:

Copy
        
1 ALTER TABLE my_table 2 DROP CONSTRAINT my_table_pkey, 3 ADD PRIMARY KEY (new_column1, new_column2);

4 — Querying Primary Key Information

You can use the pg_constraint system catalog table to retrieve information about primary key constraints in your PostgreSQL database:

Copy
        
1 SELECT conname, contype, conrelid::regclass AS table_name 2 FROM pg_constraint 3 WHERE contype = 'p';

Best Practices and Considerations

When working with primary keys in PostgreSQL, consider the following best practices and considerations:

  • Depending on your use case, select the most suitable data type, such as SERIALUUID, or a composite primary key.
  • Enforce primary key constraints to maintain data trust and distinctiveness.
  • Be mindful of the implications of modifying primary key values, as this can have cascading effects on related data.
  • Understand how your primary key selection can impact query performance, especially for large data sets.

Conclusion

A PostgreSQL primary key is used to specifically identify a row in a given table. To better appreciate its capabilities, you need a tool that helps you manage databases and visually explore query results. This is where a full-featured database client like DbVisualizer comes in. In addition to being able to connect to several DBMSs, it offers advanced query optimisation functionality, and full support for all database features, including PostgreSQL primary key.

There’s no better way to practice than using an SQL client like DbVisualizer. Its used by popular companies from Meta and Uber to NASA.

Download DbVisualizer for free now! Take an expo of all of our features, the Pro version of DbVisualizer is free for 21 days, so get your free trial now, and until next time.

FAQ

What is a primary key in PostgreSQL?

A primary key in PostgreSQL is a column or a set of columns that uniquely identifies each row in a table. It ensures data integrity by enforcing the uniqueness and non-nullability of the values in the key.

Can I drop the primary key of a table?

Yes, you can drop the primary key of a table using the ALTER TABLE statement with the DROP CONSTRAINT clause. Be cautious, however, when dropping a primary key as it can have implications on data and dependent objects.

Can I drop the primary key of a table?

Yes, you can drop the primary key of a table using the ALTER TABLE with the DROP CONSTRAINT clause as shown here:

Copy
        
1 ALTER TABLE my_table 2 DROP CONSTRAINT my_table_pkey;

Where can I grab a free trial for DbVisualizer?

Our free trial is valid for 21 days only. Observe the possibilities offered by a PostgreSQL primary key here.

Dbvis download link img
About the author
Leslie S. Gyamfi.
Leslie S. Gyamfi
Leslie Gyamfi is a mobile/web app developer with a passion for creating innovative solutions. He is dedicated to delivering high-quality products and technical articles. You can connect with him on LinkedIn
The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

SQL CHECK Constraint: Definitive Guide With Examples

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-16
title

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

How to Find Elements In an Array: PostgreSQL Guide

author Antonello Zanini tags POSTGRESQL 3 min 2024-12-05
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

List of SQL Reserved Words in All Major Databases

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 16 min 2024-11-20
title

SQL Variable: What It Is and How To Use It

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-11-18
title

Postgres DATEDIFF Equivalent Functions: Calculating Date and Time Differences

author Lukas Vileikis tags POSTGRESQL 6 min 2024-11-04
title

CREATE SCHEMA PostgreSQL Statement: What, Why & When to Use

author Lukas Vileikis tags POSTGRESQL 4 min 2024-10-30
title

SQL EXPLAIN: The Definitive Tool to Optimize Queries

author Antonello Zanini tags MySQL POSTGRESQL SQL 12 min 2024-10-29

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.