Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - create an auto-increment column for non-primary key

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?

like image 260
alextc Avatar asked Jul 24 '18 05:07

alextc


People also ask

Is there auto increment in PostgreSQL?

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 .

How do you add primary key if not exists PostgreSQL?

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.

Can you Autoincrement varchar?

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".


2 Answers

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.

like image 184
Laurenz Albe Avatar answered Nov 14 '22 23:11

Laurenz Albe


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.

like image 24
Tim Biegeleisen Avatar answered Nov 14 '22 23:11

Tim Biegeleisen