简体   繁体   中英

Alter auto-generated sequence

I use this to create auto-incremented id columns:

  id  BIGSERIAL                                -- psql
  id  BIGINT GENERATED BY DEFAULT AS IDENTITY  -- hsql

Now in unit tests i'd like to reset those sequences between tests.

Is this possible? I target PostgreSQL and HSQLDB

For PostgreSQL, you can use the pg_get_serial_sequence function to discover the name of the underlying sequence used to maintain the auto-increment, and the setval function to then manipulate it, eg to make the sequence match the highest value in the table after manually inserting or deleting rows:

Select setval(
    pg_get_serial_sequence('table_name', 'column_name'),
    (Select Max(column_name) From table_name),
    TRUE
);

The "true" is optional (default behaviour); it tells the sequence the value provided has been used, and to increment before providing the next value. See the Postgres documentation

On an empty table, you want the next value to be 1, but 0 is out of range, so you would pass FALSE:

 Select setval(pg_get_serial_sequence('table_name', 'column_name'), 1, FALSE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM