Home > Database > Mysql Tutorial > How Can I Reset a Postgres Primary Key Sequence Out of Sync with Table Rows?

How Can I Reset a Postgres Primary Key Sequence Out of Sync with Table Rows?

Mary-Kate Olsen
Release: 2025-01-23 11:41:10
Original
310 people have browsed it

How Can I Reset a Postgres Primary Key Sequence Out of Sync with Table Rows?

Resolving PostgreSQL Primary Key Sequence Discrepancies

A primary key sequence misaligned with your table's rows can cause frustrating duplicate key errors. This often happens during data imports or restores where sequence integrity isn't preserved. Here's how to fix it:

1. Find the Highest ID:

Use the MAX() function to identify the largest ID in your table:

<code class="language-sql">SELECT MAX(id) FROM your_table;</code>
Copy after login

2. Get the Sequence's Next Value:

This query shows the sequence's next generated value:

<code class="language-sql">SELECT nextval('your_table_id_seq');</code>
Copy after login

3. Reset the Sequence (If Needed):

If the sequence's next value is smaller than the table's maximum ID, reset the sequence within a transaction to prevent concurrent inserts:

<code class="language-sql">BEGIN;
LOCK TABLE your_table IN EXCLUSIVE MODE;
SELECT setval('your_table_id_seq', (SELECT GREATEST(MAX(your_id), nextval('your_table_id_seq') - 1) FROM your_table));
COMMIT;</code>
Copy after login

Source: Adapted from a Ruby Forum discussion.

The above is the detailed content of How Can I Reset a Postgres Primary Key Sequence Out of Sync with Table Rows?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template