-1

I have table user (id, firstname, lastname) and id is defined as

id int8 NOT NULL DEFAULT nextval('user_id_seq'::regclass)

But when I first insert a row through database using this SQL:

INSERT INTO user (id, firstname, lastname) 
VALUES((SELECT(MAX(id) + 1) FROM user), firstname, lastname);

the data gets inserted, but when I am hitting through API then id is not returned, I get an error

duplicate key value violates unique constraint 'user_pkey'

This is because in the previous insertion through database sequence is not updated.

How to resolve this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Suhan
  • 11
  • 1
  • The sqecuence is only used if you do not explicitly give the id – Jens Sep 07 '22 at 08:04
  • Please share more details. Is this a MySQL problem, or a PostgreSQL problem? And how is this related to [tag:create-table]? – Nico Haase Sep 07 '22 at 08:09
  • 2
    You're not supposed to insert an id value when the column already has a nextval default value. Simply do `INSERT INTO user (firstname,lastname) VALUES ('firstname', 'lastname')`. – jarlh Sep 07 '22 at 08:13
  • 1
    A `default` value is used when **no** value is specified during an INSERT. You are providing a value for the `id` column, so the `default` isn't used. Additionally: the `max(id)+1` approach will fail if you have concurrent transactions. And finally: `identity` columns are the recommended approach to auto-generate primary key values –  Sep 07 '22 at 08:23
  • @a_horse_with_no_name Is there any way I could get the sequence updated even if someone gives id? or by changing Id Default value? – Suhan Sep 07 '22 at 08:25
  • https://stackoverflow.com/questions/244243/how-to-reset-postgres-primary-key-sequence-when-it-falls-out-of-sync –  Sep 07 '22 at 08:28
  • yeah i reset the sequence at once but how can I maintain sequence updated even if someone insert along id in future? – Suhan Sep 07 '22 at 10:37

1 Answers1

1

The only good way to prevent that is to use an identity column instead:

ALTER TABLE tab
   ALTER id
   ADD GENERATED ALWAYS AS IDENTITY (START 1000000);

That automatically creates a sequence, and a normal insert statement is not allowed to override the default.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263