After restoring a Postgres database from a logical backup, inserts fail with "ERROR: duplicate key value violates unique constraint "orders_pkey" DETAIL: Key (id)=(1043) already exists."
IntermediateTroubleshootingData loss and corruption
Answer
Likely causes → The data was restored but the sequences behind the id columns weren't (or were restored to an older value), so nextval() returns IDs that already exist. Common with table-only dumps or hand-built copy scripts.
Diagnose →
SELECT max(id) FROM orders;
SELECT last_value FROM orders_id_seq;
Fix → Move each sequence past its table's maximum:
SELECT setval(pg_get_serial_sequence('orders','id'), (SELECT COALESCE(max(id),1) FROM orders));
Script it for all tables with serial or identity columns.
Prevent → Restore with full pg_dump/pg_restore (sequences included), add a post-restore check that compares sequence values to table maximums, and consider UUIDs or identity columns managed by the restore tool.
More on Data loss and corruption
An engineer ran `DELETE FROM orders;` on the production Postgres (forgot the `WHERE`) at 14:32.BeginnerA cleanup script deleted every object under `s3://acme-invoices/2025/`. Versioning is enabled.BeginnerYou need to restore last night's MySQL backup and discover the dump files for the past three months are 20 KB each.IntermediateUsers update their profile, the page reloads, and they see the old values; a minute later the new values show up.IntermediateA network partition between data centres lasted 4 minutes; afterwards you find both sites accepted writes as primary, and the same order IDs exist with different contents.AdvancedA deploy ran a migration that dropped the `phone` column; old pods still running during the rolling update threw 500s, and a background job wrote nulls into a new table.Intermediate