PostgreSQL: duplicate key value violates unique co

2019-04-24 09:42发布

问题:

When doing an UPDATE query, we got the following error message:

ERROR:  duplicate key value violates unique constraint "tableA_pkey"
DETAIL:  Key (id)=(47470) already exists.

However, our UPDATE query does not affect the primary key. Here is a simplified version:

UPDATE tableA AS a
SET
    items = (
        SELECT array_to_string(
            array(
                SELECT b.value
                FROM tableB b
                WHERE b.a_id = b.id
                GROUP BY b.name
            ),
            ','
        )
    )
WHERE
    a.end_at BETWEEN now() AND  now() - interval '1 day';

We ensured the primary key sequence was already synced:

\d tableA_id_seq

Which produces:

    Column     |  Type   |          Value           
---------------+---------+--------------------------
 sequence_name | name    | tableA_id_seq
 last_value    | bigint  | 50364
 start_value   | bigint  | 1
 increment_by  | bigint  | 1
 max_value     | bigint  | 9223372036854775807
 min_value     | bigint  | 1
 cache_value   | bigint  | 1
 log_cnt       | bigint  | 0
 is_cycled     | boolean | f
 is_called     | boolean | t

Looking for maximum table index:

select max(id) from tableA;

We got a lower value:

  max  
-------
 50363
(1 row)

Have you any idea on why such a behavior? If we exclude the problematic id, it works.

Another strange point is that replacing the previous UPDATE by:

UPDATE tableA AS a
SET
    items = (
        SELECT array_to_string(
            array(
                SELECT b.value
                FROM tableB b
                WHERE b.a_id = b.id
                GROUP BY b.name
            ),
            ','
        )
    )
WHERE a.id = 47470;

It works well. Are we missing something?

EDIT: triggers

I have no user-defined triggers on this table:

SELECT t.tgname, c.relname
FROM pg_trigger t
JOIN pg_class c ON t.tgrelid = c.oid
WHERE
    c.relname = 'tableA'
    AND
    t.tgisinternal = false
;

Which returns no row.

Note: I am using psql (PostgreSQL) 9.3.4 version.

回答1:

Not really sure what was the cause. However, deleting the two (non vital) records corresponding to already existing ids (?) solved the issue.