I am with PostgreSQL 9.5 X64 integrated with the open-source Parse Server. My table has the following structure.
objectId (text with fixed 10 characters),
item_id (integer),
item_name (text with various length)
The objectId
is the primary key due to use of Parse Server. It is automatically generated by Parse Server. The item_id
is not a primary key. I would like to have item_id
automatically increment by 1 when a new record is created. How can this be achieved in Create Table?
By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .
CREATE TABLE IF NOT EXISTS "mail_app_recipients" ( "id_draft" Integer NOT NULL, "id_person" Integer NOT NULL ) WITH (OIDS=FALSE); -- this is OK ALTER TABLE "mail_app_recipients" ADD PRIMARY KEY IF NOT EXISTS ("id_draft","id_person"); -- this is problem since "IF NOT EXISTS" is not allowed.
yes that would be possible by server script in PHP you can do like $new_auto_increment=$last_id_fetched_from_database+1; $id="BR000".
Add a default value with a sequence:
CREATE SEQUENCE mytable_item_id_seq OWNED BY mytable. item_id;
ALTER TABLE mytable ALTER item_id SET DEFAULT nextval('mytable_item_id_seq');
To make that work, you have to exclude the item_id
column from all INSERT
statrments, because the default value is only used if no value is specified for the column.
You may try making the item_id
column SERIAL
. I don't know whether or not it's possible to alter the current item_id
column to make it serial, so we might have to drop that column and then add it back, something like this:
ALTER TABLE yourTable DROP COLUMN item_id;
ALTER TABLE yourTable ADD COLUMN item_id SERIAL;
If there is data in the item_id
column already, it may not make sense from a serial point of view, so hopefully there is no harm in deleting it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With