I need to create a custom sequence based on a specific column, added as a prefix. I know it is possible to customize the sequence as well as the nextval, but I'm not sure if it is possible to use the column of a specific table.
This is the structure of the table with the essential information:
create table tab
(
id serial not null
constraint tab_pkey primary key,
year varchar(4) not null,
seq varchar(20) not null
);
create sequence tab_id_seq as integer;
I would like to automatically populate the "seq" column, as happens for normal sequences, according to this format:
{year}_{sequence}
where {year}_ is the prefix, while {sequence} is a progressive that starts again from 1 every year.
DESIRED RESULT
|--------|----------|---------|
| id | year | seq |
|--------|----------|---------|
| 10 | 2019 | 2019_1 |
|--------|----------|---------|
| 11 | 2019 | 2019_2 |
|--------|----------|---------|
| 12 | 2019 | 2019_3 |
|--------|----------|---------|
| 13 | 2019 | 2019_4 |
|--------|----------|---------|
| 14 | 2020 | 2020_1 | <--- sequence restarting
|--------|----------|---------|
| 15 | 2020 | 2020_2 |
|--------|----------|---------|
| 16 | 2020 | 2020_3 |
|--------|----------|---------|
N.B. there is no direct relationship between the id column and {sequence} element