Chances are this table of yours is created with a like clause, i.e., out of a table template.
I use table templates a lot, to factorize some common columns, and I have found that if you include the primary key into the template then only one sequence generator is used for all of the derived tables.
This has two drawbacks:
- maybe this is not the expected behaviour as you planned an individual sequence for each derived table.
- when you run
pg_get_serial_sequence() with the name of the derived table you get a null result.
Here you have a complete example, where table1 and table2 are derived from a table template named template_basic, including a sequence on id, and table3 is a normal table.
drop table if exists table3 cascade;
drop table if exists table2 cascade;
drop table if exists table1 cascade;
drop table if exists template_basic cascade;
-- The template table
create table template_basic (
id serial,
title varchar,
created_dt timestamp,
primary key (id)
);
-- A table derived from template_basic
create table table1 (
like template_basic including all,
phone_number varchar,
city varchar,
country varchar
);
-- Another table derived from template_basic
create table table2 (
like template_basic including all,
first_name varchar,
family_name varchar
);
-- A normal table, but with an equivalent structure to table1 and table2
create table table3 (
id serial,
title varchar,
created_dt timestamp,
phone_number varchar,
city varchar,
country varchar,
primary key (id)
);
-- Populate
insert into table1 default values;
insert into table1 default values;
insert into table1 default values;
insert into table2 default values;
insert into table2 default values;
insert into table2 default values;
insert into table3 default values;
insert into table3 default values;
insert into table3 default values;
Now, if you inspect these three tables you will see how table2.id share the same sequence as table1.id. Also, table3.id has its own sequence.
select id from table1;
id|
--|
1|
2|
3|
select id from table2;
id|
--|
4|
5|
6|
select id from table3;
id|
--|
1|
2|
3|
When you retrieve the name of the sequence of table1.id or table2.id you get a null, as describe before.
select pg_get_serial_sequence ('table1', 'id');
pg_get_serial_sequence|
----------------------|
|
select pg_get_serial_sequence ('table2', 'id');
pg_get_serial_sequence|
----------------------|
select pg_get_serial_sequence ('table3', 'id');
pg_get_serial_sequence|
----------------------|
public.table3_id_seq |
To get the sequence of those two tables you have to invoke the template table name.
select pg_get_serial_sequence ('template_basic', 'id');
pg_get_serial_sequence |
----------------------------|
public.template_basic_id_seq|
CREATEscripts for all tables involved and the code where you usepg_get_serial_sequence()