Jose: Hi guys and welcome back.
In this video we're looking at
autoincrementing columns in Postgres
and the types sequence and serial.
What is a sequence?
In Postgres, a sequence is a number generator.
It's really a table with one column and one row,
so just one cell of data,
and the value in that cell starts off as the number one
and Postgres has a bunch of operations to increase the value
or to get the current value, and so on.
So for example, we've got these here,
CREATE SEQUENCE my_sequence.
That creates a new table with that value.
SELECT currval of my_sequence would give you
the current value in that table.
SELECT nextval of my_sequence
would increase the value by one and give you the next value.
And so these operations here are used to operate
on sequences instead of changing the value yourself.
That way you always know that the value you're getting
is unique because it always increases by one
and it's always in order.
You know, one by one.
And so, when you're creating a sequence
you want to always use these functions
instead of doing it yourself.
So what is serial?
Well, it's a shortcut.
You can use it as a data type when creating a table
instead of the integer data type
for your primary key, for example.
And it'll automatically create the sequence table for you
and increase it's value every time
a new row is added on this table.
That new value will be used by default
when adding new rows.
So just as we did in SQLite, you know,
user ID integer primary key, for example,
we're now gonna do user ID serial primary key
and it's gonna work in basically the same way.
Some difference though is that the sequence
always increases one by one.
And remember, that in SQLite
row IDs could use repeated values,
and that won't happen in Postgres.
All right, thank you guys for joining me for this video.
Thanks for watching
and I'll see you in the next one.