SoFunction
Updated on 2025-04-07

Detailed steps to set the primary key to increase from 1

Unlike MySQL, in PostgreSQL, setting the primary key to start from 1 and start from self-increase again is achieved through sequences. Here are the steps:

Step 1: Create a Sequence

CREATE SEQUENCE your_table_id_seq
    START 1
    INCREMENT 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

In the above code,your_table_id_seqis the name of the sequence, you need toyour_tableReplace with your actual table name.START 1It means that it starts from 1,INCREMENT 1Indicates incrementing by 1 each time.

Step 2: Associate the sequence with the columns of the table

Suppose your table's primary key column name isid, associate the created sequence with this column:

ALTER TABLE your_table
    ALTER COLUMN id
    SET DEFAULT nextval('your_table_id_seq'::regclass);

Step 3: Use default values ​​when inserting data

When inserting data, you do not need to specify a value for the primary key, and the database will automatically use the next value of the sequence:

INSERT INTO your_table (column1, column2, ...)
VALUES (value1, value2, ...);

Step 4: Query the value that increases

To query the current self-incremented value, you can usecurrvalfunction:

SELECT currval('your_table_id_seq'::regclass);

Step 5: Start increasing again

If you want to start adding again, you can usesetvalfunction:

SELECT setval('your_table_id_seq', 1, false);

The above code sets the current value of the sequence to 1. The last parameterfalseIndicates that the new value is not used immediately, if set totrue, the new value will be used immediately.

Please make sure to make appropriate replacements based on your actual table and column names.

This is the article about PostgreSQL setting the primary key to increase from 1. For more related PostgreSQL setting the primary key to increase from 1, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!