Current value of an "auto increment" field in Postgresql

Asked

Viewed 522 times

1

I would like to know, what are the ways of obtaining the current position of the value "auto increment" of columns of a table in the Postgresql.

2 answers

1


The field type "Auto Increment" of Postgres is called SERIAL field INT and BIGSERIAL field BIGINT.

The command to create this column type is:

ALTER TABLE tabela ADD coluna SERIAL NOT NULL;

When creating this type of column, the database creates an internal SEQUENCE and sets the column default value as the next value of that SEQUENCE. (more information about sequences at this link)

The name of SEQUENCE created for fields of the type SERIAL follows the format:

table + '_' + spine + '_seq'

To get the current value of the column, you need to know the name of the SEQUENCE corresponding, and then use the command CURRVAL:

SELECT CURRVAL('nome_da_sequence');

So, the guy SERIAL is nothing more than a "shortcut" to the following command:

-- Criar uma coluna
ALTER TABLE tabela ADD COLUMN coluna INT NOT NULL;
-- Cria uma sequence que depende da coluna (OWNED BY), 
-- ou seja, quando a coluna for excluída, a sequence também será
CREATE SEQUENCE tabela_coluna_seq OWNED BY tabela.coluna;
-- Configurar o próximo valor da sequence (NEXTVAL) como o valor padrão da coluna
ALTER TABLE tabela ALTER COLUMN coluna SET DEFAULT NEXVAL('tabela_coluna_seq');

It is also possible to obtain the SEQUENCE field-type SERIAL using the function pg_get_serial_sequence. Would look like this:

SELECT CURRVAL(pg_get_serial_sequence('tabela', 'coluna'))

1

In the PostgreSQL an "auto increment is a field with data type serial or bigserial.

A guy serial is nothing more than a whole with a sequence associated.

To manipulate sequences you have the following functions: currval(regclass), lastval(), nextval(regclass), setval(regclass, bigint) and setval(regclass, bigint, boolean).

For more details see documentation.

  • anonymity, your answer is partially correct. Missing an example of each, to get a good response and have good content on the site. That was the idea, to ask the question because it is not here in Sopt. I await its edition :)

  • You mean repeat what is in the documentation of the indicated software?

  • No... more details, examples of usage, a test, a db-fiddle, etc.Something well explained, exemplified, showing usage, so it will help many who enter here and see the topic. Automatically, you will get more votes!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.