Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Default values
How to auto-generate values in a database
14. SEQUENCE – explanation

Instruction

Very nice! There's another way to generate unique integer values in PostgreSQL: using a sequence. A sequence is a database object that generates unique consecutive integers. We create a sequence like this:

CREATE SEQUENCE author_seq
  START WITH 1
  INCREMENT BY 1;

We can get an integer value from the author_seq sequence using this command:

SELECT NEXTVAL('author_seq');

If this is the first time we've specified author_seq, the result will be 1. The default start value for sequences is 1, and the default increment value is 1. Running the query above a second time returns 2, a third time returns 3, and so on.

The creator of the sequence can set the start or increment value to another value, even a negative one. For example, if we start with -120 and increment by -2, we'd get -120, -122, -124, etc.

Exercise

Run the template to see how a sequence generates a new value.