snippetsqlMinor
How do you reset a serial type back to 0 after deleting all rows in a table?
Viewed 0 times
afterrowsdeletingyoualltabletypeserialbackhow
Problem
I previously asked this question , and somebody posted a very helpful answer on db fiddle here. This has worked really well for me. However, now I would like to ask a new (related) question :
Suppose I wipe out all the rows in the table (i.e. in the db fiddle example the apple and orange rows are deleted by doing "delete from fruits where id > 0"). If I insert another fruit like watermelon, the id will start at 4, not 1. How do I force the id type to reset back to 0, so that the next insert will have id=1 ?
Suppose I wipe out all the rows in the table (i.e. in the db fiddle example the apple and orange rows are deleted by doing "delete from fruits where id > 0"). If I insert another fruit like watermelon, the id will start at 4, not 1. How do I force the id type to reset back to 0, so that the next insert will have id=1 ?
Solution
Simple (assuming you know the sequence name):
Or:
Safe (you don't know the sequence name or are not certain whether the table is empty):
db<>fiddle here
Of course, that's still not safe under concurrent write load - where you shouldn't mess with the sequence like this at all.
See:
SELECT setval('fruits_id_seq', 1, false);Or:
ALTER SEQUENCE payments_id_seq RESTART WITH 0;Safe (you don't know the sequence name or are not certain whether the table is empty):
SELECT setval(pg_get_serial_sequence('fruits', 'id')
, COALESCE(max(id) + 1, 1)
, false)
FROM fruits;db<>fiddle here
Of course, that's still not safe under concurrent write load - where you shouldn't mess with the sequence like this at all.
See:
- How to reset Postgres' primary key sequence when it falls out of sync?
- Postgres manually alter sequence
- How to fix all duplicate key values from sequences?
Code Snippets
SELECT setval('fruits_id_seq', 1, false);ALTER SEQUENCE payments_id_seq RESTART WITH 0;SELECT setval(pg_get_serial_sequence('fruits', 'id')
, COALESCE(max(id) + 1, 1)
, false)
FROM fruits;Context
StackExchange Database Administrators Q#308316, answer score: 6
Revisions (0)
No revisions yet.