Interview Prep/Real-World Interview/Data loss and corruption

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.

All Real-World Interview questions Roadmap: Interview readiness

More on Data loss and corruption