How to make a sequence in postgres
Postgres has inbuilt capability to generate and keep track of sequences. These are usually used for generating some form of key and associating that key with a column. Intuitively, they are similar to Python iterators in the sense you can generate and then consume values with next() like syntax.
#Example
You can create a sequence with:
CREATE SEQUENCE sequence_name;
and then associate that sequence with:
CREATE TABLE table_name (
id INTEGER DEFAULT nextval('sequence_name'),
-- ... other things
);
#Customizing the sequence
You can control how the sequence generates with:
CREATE SEQUENCE my_sequence
AS integer
INCREMENT 42
MINVALUE 84
MAXVALUE 12345678
START 10
CACHE 100
NO CYCLE;
STARTspecifies the starting value for the sequence.INCREMENTspecifies the amount by which the sequence value increases (or decreases).MINVALUEandMAXVALUEdefine the minimum and maximum values the sequence can generate.CACHEsets how many sequence values are stored in memory before accessCYCLEallows the sequence to wrap around to the minimum value when it reaches the maximum value (or vice versa). Note whenCYCLEis not set, thenextval()will error when reachingMAXVALUE + 1
#How to decrement a sequence
Use INCREMENT -1
CREATE SEQUENCE decreasing_sequence INCREMENT -1