Question
In such a situation, after creating a table and inserting data, the id
has reached 5, for example. If you delete all 5 rows, the next id
will be 6. Is it possible to make it start from 1? Reset the id
counter.
Answer
id
are unique and sequential, but they can have GAPS! This is because id
is reserved at the start of a transaction, and if it is restarted, for example, during concurrent access, the id
is not rolled back but the next available one is taken.
If you duplicate id
, the table will become non-functional due to an SQL error.
How to reset the last id
:
Connect to the database:
sudo -u postgres psql -d totum
Set a new last number:
Replace SCHEMA_NAME
, NUMBER_HERE
, and NAME_TABLE
with your values;
SELECT setval('SCHEMA_NAME.NAME_TABLE_id_seq', NUMBER_HERE);
You cannot set it to 0
, the minimum value is 1
. So if you want to reset the rows, the first row in this case will have id = 2
.
Exit:
\q