Is there an existing implementation of the reverse "AUTO_INCREMENT" in PostgreSQL or MySQL?

Without having to do this manually (I am open to implementation if there are no other options), is there a way in PostgreSQL or MySQL to have an automatic counter / field in which increments are reduced ?

For various reasons, in the current application it would be nice to know how many more records (in terms of data type) can still be added to the table by simply looking at the most recently added record, instead of subtracting the last identifier from max for the data type.

So, is there " AUTO_DECREMENT " or similar for any system?

+4
source share
1 answer

In PostgreSQL, you need to set it up a bit manually, but you can set up this sequence:

 create sequence example_seq increment by -1 minvalue 1 maxvalue 5 start with 5; create table example( example_id int primary key default nextval('example_seq'), data text not null ); alter sequence example_seq owned by example.example_id; 

I believe that it would be equivalent to creating a table with a serial column, and then modify the automatically generated sequence.

Now, if I insert some rows, I get example_id, counting from 5. If I try to insert more than 5 rows, I get nextval: reached minimum value of sequence "example_seq" (1)

+6
source

Source: https://habr.com/ru/post/1392136/


All Articles