Re: Issue Report: Unique Constraint Violation Error in PostgreSQL

From: Francisco Olarte <folarte(at)peoplecall(dot)com>
To: "sing_hijo(at)outlook(dot)com" <sing_hijo(at)outlook(dot)com>
Cc: pgsql-bugs <pgsql-bugs(at)lists(dot)postgresql(dot)org>
Subject: Re: Issue Report: Unique Constraint Violation Error in PostgreSQL
Date: 2024-06-12 11:56:02
Message-ID: CA+bJJbwvDuh31mz5VC_f_zfkgdi2AKAJu_NJVnEHLOnxbQo+XA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On Wed, 12 Jun 2024 at 11:33, sing_hijo(at)outlook(dot)com
<sing_hijo(at)outlook(dot)com> wrote:
...
> Problem Description:
> I encountered a unique constraint violation error when attempting to insert data into a table.

You forced a constraint violation, it is a misunderstanding, not a bug:

> CREATE TABLE test_table (
> id bigserial PRIMARY KEY,
This means 1.- Column gets a default from a sequence + 2.- column is a
primary key.
> name varchar
> );
...
> INSERT INTO test_table (name) VALUES ('test1, no insert id');
- This is getting the default value from the sequence ( normally 1 ).
> INSERT INTO test_table VALUES (2, 'test2, insert id');
- This inserts 2, the sequence is not consulted.
> INSERT INTO test_table (name) VALUES ('test3, no insert id');
- And this is asking to insert the default sequence value, which is 2
because you used 1 above.
> Result:
> Error message: [23505] ERROR: duplicate key value violates unique constraint "test_table_pkey" Detail: Key (id)=(2) already exists.

Yep, your second stament is the same as inserting an explicit 2. So
dupe key is expected behaviour. Bug will be not getting it.

> Expected Result:
> I expected the data to be inserted successfully without encountering a unique constraint violation.
Wrong expectation. Sequences do not magically notice you have stomped
over their values. Someone posted a soluction if you need to do
something like this ( it is usual in bulk loading, you load explicit
values, then calculate max used value and set it as last value for the
sequence ).

Francisco Olarte.

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Stefan Heine 2024-06-12 13:47:44 Re: BUG #18503: Reproducible 'Segmentation fault' in 16.3 on ARM64
Previous Message Muhammad Ikram 2024-06-12 09:59:05 Re: Issue Report: Unique Constraint Violation Error in PostgreSQL