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_seq
is the name of the sequence, you need toyour_table
Replace with your actual table name.START 1
It means that it starts from 1,INCREMENT 1
Indicates 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 usecurrval
function:
SELECT currval('your_table_id_seq'::regclass);
Step 5: Start increasing again
If you want to start adding again, you can usesetval
function:
SELECT setval('your_table_id_seq', 1, false);
The above code sets the current value of the sequence to 1. The last parameterfalse
Indicates 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!