0

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
Andrus
  • 26,339
  • 60
  • 204
  • 378

1 Answers1

1

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • This code leaves old data in table. New time, ip address and user should inserted. Old values should replaced. Also code should run in Postgres 9 versions also. – Andrus Mar 03 '21 at 15:53
  • 1
    @Andrus . . . Your question is: "How to fix this ? " This answers the question you have asked in this question for all supported versions of Postgres. If you have a different question, ask a *new* question with a clear explanation (sample data and desired results help). If you are using an unsupported version of Postgres, please explain why. – Gordon Linoff Mar 03 '21 at 15:56
  • 1
    @Andrus add to your question exactly which PostgreSQL version your query needs to run. Upserts were introduced in 9.5 (which is btw already EOL): https://endoflife.software/applications/databases/postgresql – Jim Jones Mar 03 '21 at 16:02
  • Code in question causes exception is supported Postgres 13.1 It deletes possible existing key before adding and must work as it is. I need to use it starting from postgres 9.0 since some customers are using this version and dont want to upgrade. – Andrus Mar 03 '21 at 20:07
  • @GordonLinoff Your answer produces wrong result. In case of conflict your code does not update data in table and leaves old wrong content in table. Changed question title to `How to fix duplicate key value violates unique constraint error in Postges 9+`. Customers are using different Postgres versions starting at 9.0 and dont want to upgrade. – Andrus Mar 03 '21 at 20:09