Search code examples
sqlwindowspostgresqlduplicatespsqlodbc

How to fix duplicate key value violates unique constraint error in Postges 9+


Sometimes strange duplicate key error

duplicate key value violates unique constraint "session_pkey"
Key (workplace)=(WIN-N9BSKUNKBC8 ) already exists.

Occurs in script:

delete from session where workplace='WIN-N9BSKUNKBC8' ;
INSERT INTO session (workplace,ipaddress,logintime,loggeduser)
SELECT 'WIN-N9BSKUNKBC8' , inet_client_addr()::CHAR(14),current_timestamp::CHAR(28),CURRENT_USER WHERE NOT EXISTS (SELECT 1 FROM session WHERE workplace='WIN-N9BSKUNKBC8' )

Sript is running form windows task scheduler on every 10 minutes. Error occurs only sometimes.

How to fix this ? Table is defined as

CREATE TABLE public.session
(
    loggeduser character(10) ,
    workplace character(16) NOT NULL,
    ipaddress character(20) ,
    logintime character(28) ,
    activity timestamp with time zone,
    CONSTRAINT session_pkey PRIMARY KEY (workplace)
)

Environment:

PostgreSQL 13.1, compiled by Visual C++ build 1914, 64-bit
Windows server 2019
psqlODBC driver 13.00.0000

Solution

  • You can use on conflict:

    INSERT INTO session (workplace,ipaddress,logintime,loggeduser)
        SELECT 'WIN-N9BSKUNKBC8',     
              inet_client_addr()::CHAR(14),current_timestamp::CHAR(28),
    CURRENT_USER 
        ON CONFLICT DO NOTHING;
    

    Given that you have only one row going in, my guess is that the problem is due to concurrency issues.