How to Reset Auto Increment Counter in PostgreSQL?
Last Updated :
30 Oct, 2024
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 orderly assignment of unique identifiers, which helps maintain data integrity and database optimization.
In this article, we will explain how to reset the auto-increment counter in PostgreSQL using different approaches, including the ALTER SEQUENCE command and the SETVAL function. We’ll provide detailed examples for each method.
How to Reset the Primary Key Sequence ID in PostgreSQL?
In PostgreSQL, an auto-increment counter is commonly implemented using a sequence object. Sequences are database objects designed to generate unique sequential numbers, which are often used as primary key values in database tables. This auto-increment functionality is typically achieved with the SERIAL
data type.
- Using the ALTER SEQUENCE command
- Using the TRUNCATE command
Creating a Sample Table
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.
Query:
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
DATA1. Using the ALTER SEQUENCE command
The ALTER SEQUENCE command in PostgreSQL is used to change and modify the properties of a created sequence. In PostgresSQL, Sequences are database objects that mainly generate unique sequential numbers, & generated Id's are used as primary key values in Database operations.
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)
Key Terms
- 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.
Query:
-- 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));
Output
SETVAlExplanation:
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.
Conclusion
In summary, resetting the auto-increment counter in PostgreSQL is essential for managing primary key sequences effectively. We covered two primary methods: using the ALTER SEQUENCE command and the SETVAL function along with pg_get_serial_sequence. Both methods allow for efficient management of sequence values, ensuring data integrity and smooth operations in your PostgreSQL databases.
Similar Reads
How to Reset Auto Increment in MySQL
Resetting the AUTO_INCREMENT value is a common operation, often required during development, testing, or database maintenance. We use the ALTER TABLE statement to reset the AUTO_INCREMENT property in MySQL. We can also use the TRUNCATE TABLE statement or use the DROP TABLE and CREATE TABLE statement
3 min read
How to Create Id with AUTO_INCREMENT in SQL Server?
Structured Query Language also known as SQL is a tool for storing, managing, and manipulating relational databases. SQL Server is a popular relational database management system (RDBMS) developed by Microsoft, providing a variety of operators to perform different operations on given datasets. In thi
4 min read
How to Create id With AUTO_INCREMENT in PL/SQL?
PL/SQL, short for Procedural Language/Structured Query Language, combines SQL capabilities with procedural programming. It supports variable declaration, control flow structures, functions, records, cursors, procedures, and triggers. PL/SQL features a block structure with optional sections for varia
5 min read
PostgreSQL - Create Auto-increment Column using SERIAL
In PostgreSQL, the SERIAL data type is a convenient way to create auto-increment columns, commonly used for primary keys. This feature simplifies the process of generating unique identifiers automatically without requiring additional manual input. By using SERIAL, BIGSERIAL, or SMALLSERIAL, PostgreS
4 min read
How to Create id with AUTO_INCREMENT in MySQL?
Primary keys in databases uniquely identify each record, ensuring data integrity and efficient retrieval. AUTO_INCREMENT, a feature in MySQL, automatically assigns unique numeric identifiers to new rows, simplifying data management. Understanding these concepts is crucial for designing robust databa
6 min read
How to Add Prefix in Auto Increment in MySQL?
In MySQL, you might need to create unique identifiers that combine a static prefix with an auto-incrementing number, such as order numbers or user IDs. This article provides a simple guide on how to set up a table and use a trigger to automatically generate these concatenated values. By following th
3 min read
How to Use Count With Condition in PostgreSQL?
In PostgreSQL, the COUNT() function serves as a tool for tallying the number of records within a table. This article aims to address this query, delving into the nuances and implications of integrating conditions into the COUNT() function in PostgreSQL. The COUNT() function in PostgreSQL is traditio
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 Remove All Duplicate Rows Except One in PostgreSQL?
When working with databases, we often have duplicate rows in the table. These duplicates can arise due to various reasons such as erroneous data entry or data migration processes. Removing duplicates while retaining one instance of each is a frequent requirement in database maintenance tasks. So to
5 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