In today’s article, I will be explaining how to Use Sequence of Different Table in PostgreSQL.
We create our first table.
1 |
create table seqtable1 (id serial ,name char(100)) |
Since we gave the serial data type in the id column in the above table, a sequence named “seqtable1_id_seq” was created.
You can view the sequences to view the sequence.
We add data to our first table and see if sequence will be used.
1 2 3 |
insert into seqtable1(name) values ('faruk') insert into seqtable1(name) values ('erdem') |
We have added our data, now we are checking the data in the table.
We create our second table named Seqtable2 and while creating it, we give the nextval parameter to the id part and our sequencer consisting of the name seqtable1_id_seq.
1 |
create table seqtable2(id int not null default nextval('seqtable1_id_seq'),name char(100)) |
We add the data.
1 2 3 |
insert into seqtable2(name) values ('utku') insert into seqtable2(name) values ('erdem') |
In the Seqtable1 table, we expect the last data to be one more than the value in the id column.
Let’s see if the id column starts with 3 by pulling the select from the seqtable2 table.
If you want to use the next value with the nextval parameter in the insert sentence, you can use the command below.
1 2 3 |
Syntax: insert into tablename(column1,column2) values (nextval('sequence name'),column2data) |
Example :
1 |
insert into seqtable2 values (nextval('seqtable1_id_seq'),'ERDEM') |