All databases will have the option of an auto-incrementing column to use as the primary key column in a table. In PostgreSQL, this is done with a SEQUENCE, which is a special type of object that creates a sequence of integers. It is important to know the order of the numbers, as the sequences of 1, 2, 3, 4, 5 and 5, 4, 3, 2, 1 would be different sequences.
Sequences can have a few common parameters:
CREATE SEQUENCE <sequence_name>
[parameters];
For example, if we wanted to create a sequence named mysequence and have it start with 10, and increment it by 10, we would do the following:
CREATE SEQUENCE mysequence
START 10
INCREMENT 10;
If we wanted to get the next value from the sequence, we can use the nextval function like this:
SELECT nextval('mysequence');
You’ll notice that the first value is set to 10. If we run the same statement again, it’ll increment the value by 10:
A sequence can be automatically added to a table using the data type SERIAL. It is an important pseudo-type as it simplifies much of the complexity of creating the sequence and incrementing it. By assigning the SERIAL pseudo-type to a table, the database will do the following:
CREATE TABLE contact( contact_id SERIAL, username VARCHAR(50), password VARCHAR(50) );
Behind the scenes, it is the same as the database doing this:
CREATE SEQUENCE contact_contact_id_seq;
CREATE TABLE contact(
contact_id integer NOT NULL DEFAULT nextval(contact_contact_id_seq),
username VARCHAR(50),
password VARCHAR(50)
);
ALTER SEQUENCE contact_contact_id_seq
OWNED BY contact.contact_id;
This looks complex and has some extra commands we haven’t reviewed yet, but it follows the structure as we described above:
CREATE TABLE contact(
contact_id SERIAL PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)
);
We will explore inserting into a table with the SERIAL primary key in a later tutorial.
[MUSIC PLAYING] The primary key is quite important being that it uniquely identifies every single role within the table. There are instances where you might not have a value to make it such that it's going to be unique across the board, and you have to generate it. Therefore, you can use sequences or in Postgres you can use Acero, or it's also called an auto increment, or auto number depending on the database that you're utilizing.
In this case here, go ahead and create this table. And now if we insert it into this table, we're only going to insert into the username itself with the values of fun, coding, and SQL into the username. If we go ahead and run this statement, don't worry we'll get into the Insert statements later on, but if we go ahead now and select from the table.
[MUSIC PLAYING]
You should see that even though we didn't insert anything into the contact ID, it automatically sequences it with one, two, or three sequences work in the same way the next time that we insert into the table it'll be 4, and so forth.
[MUSIC PLAYING]
Source: Authored by Vincent Tran