How to Reset the Primary Key Sequence ID in PostgreSQL?
Last Updated :
24 Apr, 2024
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 the Primary Key Sequence ID with the help of different approaches & we will also see examples of each approach.
How to Reset the Primary Key Sequence ID in PostgreSQL?
When working with PostgreSQL process of Resetting the Primary Key Sequence ID. There are a few different approaches to resetting the primary key sequence ID in PostgreSQL, each with its advantages and disadvantages. The following approaches are:
- Using the ALTER SEQUENCE Command
- Using SETVAL and pg_get_serial_sequence
Before we delve deeper into the queries, let's create the table courses in gfg database and insert some sample values in the table. The following code creates the Sample Table and inserts the entries in the table.
CREATE DATABASE gfg;
-- Create a table
CREATE TABLE courses (
course_id SERIAL PRIMARY KEY,
course_name VARCHAR(100),
fees DECIMAL(10, 2),
instructor VARCHAR(100)
);
-- Insert some sample data
INSERT INTO courses (course_id,course_name, fees, instructor)
VALUES
(1,'Java', 10000, 'Akhil'),
(2,'Python', 15000, 'Jacky'),
(3,'C++', 20000, 'Sourav');
Output:
courses
1. Using the ALTER SEQUENCE Command
The ALTER SEQUENCE command in PostgreSQL is used to modify the properties of a sequence. Sequences are database objects that generate unique sequential numbers, typically used as primary key values.
Syntax:
ALTER SEQUENCE name [ INCREMENT [ BY ] increment ]
[ START [ WITH ] start ]
[ MINVALUE minvalue | NO MINVALUE ]
[ MAXVALUE maxvalue | NO MAXVALUE ]
[ CACHE ]
[ CYCLE | NO CYCLE ]
[ OWNED BY { table_name.column_name | NONE } ];
- name: is the name of the sequence object to be altered.
- increment: is the increment value for the sequence. If omitted, the increment value is 1.
- start: is the start value for the sequence. If omitted, the start value is the current value of the sequence.
- minvalue and maxvalue: specify the minimum and maximum values for the sequence, respectively. If omitted, the minimum and maximum values are determined by the integer, bigint, or smallint data type of the sequence.
- cache: specifies the cache size for the sequence. If omitted, the cache size is set to the default value.
- cycle: specifies that the sequence should cycle after reaching its maximum value. If omitted, the sequence does not cycle.
- owned by: specifies the table and column that own the sequence. If omitted, the sequence is owned by no table or column
Example
The following query reset the sequence to start from the next value after the maximum course_id. Assuming the sequence name is courses_course_id_seq and returns the result as before:
ALTER SEQUENCE courses_course_id_seq RESTART WITH 5;
The above query, resets the auto-increment sequence for the course_id column in the courses table to start from 5,.
Output:
ALTER_SEQUENCE2. Using SETVAL and pg_get_serial_sequence:
The setval() function in PostgreSQL is used to set the value of a sequence.
Syntax:
SETVAL(sequence_name, next_value)
- sequence_name: is the name of the sequence you want to set the value for.
- next_value: is the new value you want to set the sequence to.
Example
The following query reset the primary key sequence ID in PostgreSQL, you can use the SETVAL function along with pg_get_serial_sequence.
-- Find the name of the sequence
SELECT pg_get_serial_sequence('courses', 'course_id');
-- Reset the sequence
SELECT setval('courses_course_id_seq', (SELECT MAX(course_id)+1 FROM courses));
In the above query, SELECT pg_get_serial_sequence('courses', 'course_id'); retrieves the name of the sequence associated with the course_id column in the courses table, and the second line SELECT setval('courses_course_id_seq', (SELECT MAX(course_id)+1 FROM courses)); resets the courses_course_id_seq sequence to start from the next value after the current maximum course_id in the courses table.
Output:
SETVALConclusion
In this article, we covered How to Reset the Primary Key Sequence ID in PostgreSQL. with the help of two method, first one is the ALTER SEQUENCE command. We understood the example of the ALTER SEQUENCE command. We later looked at Using SETVAL and pg_get_serial_sequence functions and understood the ease it provide. so now you can effectively reset the primary key sequence ID in PostgreSQL and maintain the integrity of your database.
Similar Reads
How to Reset Primary Key Sequence in MySQL?
In MySQL, the primary key maintains data integrity and uniqueness. However, there are instances where the primary key sequence might fall out of sync, leading to potential issues. In this article, we'll understand the process of resetting the primary key sequence in MySQL databases with different ex
4 min read
How to Reset Primary Key Sequence in PL/SQL
Resetting a PL/SQL primary key sequence is an important task to ensure that the sequence values align with the current state of the table. When a sequence falls out of sync with the data in a table, it can lead to issues where new records receive primary key values that conflict with existing data.I
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 orig
4 min read
How to Reset SQLite Primary Key Sequence When it Falls Out of Sync?
SQLite is one of the most popular embedded database engines which uses primary keys to distinguish among different records saved in a table. However, the primary key field could become unstable as a result, the data integrity might be threatened and the functionality of the application could fail. I
3 min read
How to Reset SQL Primary Key Sequence When It Falls Out of Sync?
In SQL databases, primary keys play a critical role in maintaining data integrity and ensuring uniqueness. However, primary key sequences can sometimes fall out of sync, leading to potential issues. In this article, we'll delve into the reasons behind primary key sequence misalignment and provide a
3 min read
How to Select the Nth Row in a PostgreSQL Database Table?
In PostgreSQL, selecting specific rows is a fundamental operation frequently required for tasks such as data analysis, pagination, and reporting. The "nth" row refers to the row in a table that holds a particular position or rank, where "n" represents that specific position or ranking number. This a
5 min read
PostgreSQL - Primary Key
A primary key in PostgreSQL is a column (or a set of columns) that uniquely identifies each row in a table. It is an important component for ensuring data integrity and plays an important role in database normalization. When we define a primary key in PostgreSQL, the database automatically creates a
4 min read
How to Insert Multiple Rows to a Table in PostgreSQL?
Inserting multiple rows into a table in PostgreSQL is a common and efficient operation, especially when handling large datasets. By executing a single SQL query, multiple rows can be added simultaneously, reducing overhead and enhancing performance. This method is particularly valuable in scenarios
5 min read
How to Reset Auto Increment Counter in PostgreSQL?
PostgreSQL is a powerful, open-source, object-relational database management system (DBMS) developed by a vibrant community. One common requirement for database administrators is resetting the auto-increment counter for primary key sequences. In PostgreSQL, this process is crucial for ensuring the o
4 min read
How to get the insert ID in SQL?
When working with SQL databases, obtaining the insert ID (the auto-incremented primary key value) after inserting a new record is crucial for managing data relationships and ensuring seamless data referencing. In SQL databases, obtaining the insert ID after adding a new record to a table is a common
4 min read