concurrent insertion with unique key constraint - sql

I have a web application with multiple instance running all connected to a p-SQL with a table - myTable that have only two columns with one column is having unique key constraint.
This application will receive at least 15K request in a second from multiple instance and my requirement is to avoid the duplicate insertion in the table.
myTable:
CREATE TABLE myTable (
id SERIAL PRIMARY KEY,
myData VARCHAR (50) UNIQUE);
Insert statement:
INSERT INTO myTable (myData) VALUES ('data-1');
My question is if all the instances try to insert same data (assume the above insert statement from all the instances), all at a time to the table will I get only one record inserted and one instance will get inserted success message and all other instance will get a duplicate key error?

Related

Insert into violation of PRIMARY or UNIQUE KEY constraint Firebird 2.5

I am trying to insert a few values in an existing table, but first it makes nothing and 2nd time it shows me this error message.
My Unique KEY consists of a FK of a higher table and a counter.
If I check my tables there is no entry but it does not accept my UNIQUE Key.
Anybody with some ideas?
My test SQL Code for inserting into the view (same result with table)
INSERT INTO V_BRESZ(BRES_ID_LINKKEY, Maskenkey)
VALUES(29, 60);
For example my error message is:
violation of PRIMARY or UNIQUE KEY constraint "UK_BRESZ" on table
"BRESZ". Problematic key value is ("MASKENKEY" = ' 60',
"BRES_ID_LINKKEY" = 29).
But there is no such entry in my table / view.

Prevent duplicate key usage

Database is Postgresql. For an simplified example I will insert measurement data in various tables. Example DDL for one example table looks like this:
CREATE TABLE
measurement
(
id_meas BIGINT NOT NULL,
...
PRIMARY KEY (id_meas)
);
The process of inserting data currently works like this:
Select max id value from table
Increment id value
Insert next data row using incremented id value
This works as long as there is only one client inserting data. But what if there are > 1 client's inserting so that two clients may select 567 as max id value and both increment this to 568 as next id value to insert. In that case the second client executing the insert command will receive an duplicate key error. Is there a way to prevent those errors other than re-executing the insertion process after an error occurred?
You are looking for a serial column:
CREATE TABLE measurement (
id_meas bigserial primary key,
...
);
bigserial is a bigint that auto-increments (see here). You can also just use serial if an int is big enough.
This puts the database in charge of incrementing the value, rather than the application. You are guaranteed that race conditions will not result in the same value in different records. It is possible that gaps in the value will appear under some circumstances.

Insert new row in sql table with same foreign key value

I need to be able to insert multiple rows in a table where one of the fields, a foreign key will be included in multiple rows.
Currently when I'm trying to do insert I'm getting this error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Cannot insert duplicate key row in object
'dbo.userGroupMembership' with unique index 'IX_userId'. The duplicate
key value is (264673).
Query I'm using:
INSERT INTO userGroupMembership(userId, usergroupId, created, adultAdminAccessLevel)
SELECT [userId], 12, GETDATE(), 0
FROM [dbo].[userGroupMembership]
where usergroupId = #UserGroupId
UserId is the foreign key field.
Any idea if I need to do any configuration change in the table or how can I be able to insert multiple rows with same foreign key?
You have a unique index allowing one row per userID. If you truly want more than one row per userID just drop the unique index.
DROP INDEX dbo.userGroupMembership.IX_userID;

Duplicate key in foreign table

I have these Oracle tables:
CREATE TABLE AGENT(
ID INTEGER NOT NULL,
GROUP_ID NUMBER(38,0),
........
)
/
CREATE INDEX IX_RELATIONSHIP_AG_GROUP ON AGENT (GROUP_ID)
/
ALTER TABLE AGENT ADD CONSTRAINT AGENTID PRIMARY KEY (ID)
/
CREATE TABLE AGENT_CONFIG(
AGENT_CONFIG_ID INTEGER NOT NULL,
AGENT_ID INTEGER,
.......
)
/
CREATE INDEX IX_RELATIONSHIP16 ON AGENT_CONFIG (AGENT_ID)
/
ALTER TABLE AGENT_CONFIG ADD CONSTRAINT KEY17 PRIMARY KEY (AGENT_CONFIG_ID)
/
ALTER TABLE AGENT_CONFIG ADD CONSTRAINT RELATIONSHIP16 FOREIGN KEY (AGENT_ID) REFERENCES AGENT (ID)
/
I want to use the first table AGENT as main table to store data. Into the second table I want to store configuration about AGENT and use AGENT ID as unique ID.
But I have this problem: I insert successfully row into table AGENT. I need to also add empty row with the same ID into table AGENT_CONFIG and later update that row. How I can duplicate this ID value duplication? Probably with Oracle table trigger? Is three any other way like special relation between the tables?
I use this SQL Query for insert into AGENT table:
INSERT INTO AGENT ("ID, GROUP_ID, NAME.....) VALUES (AGENT_SEQ.nextval, ?, ......)
Is this correct query:
INSERT INTO AGENT (ID, GROUP_ID......) VALUES (AGENT_SEQ.nextval, ?.......)
RETURNING id INTO INSERT INTO AGENT_CONFIG (AGENT_SEQ.nextval, Agent_ID) VALUES (id)"
For this use currval pseudocolumn (as #Nicholas Krasnov specified) of the sequence that you are using after you use nextval for table "AGENT". Currval will duplicate the value that you used for table "AGENT".
So for example :
1. INSERT INTO AGENT (ID, GROUP_ID......) VALUES (AGENT_SEQ.nextval, .......)
2. INSERT INTO AGENT_CONFIG (AGENT_CONFIG_ID,AGENT_ID) VALUES (NULL,AGENT_SEQ.CURRVAL) ;
Link for Sequence Pseudocolumns --> https://docs.oracle.com/cd/B28359_01/server.111/b28286/pseudocolumns002.htm
To establish a 1:1 or 1:{1,n} relation is not that easy:
On every insert in the parent table you'd have to make sure an according insert in the child table is also made.
On every delete from the parent table you'd have to make sure to delete the according child records (usually via cascading delete or by mere foreign key constraints).
On every delete from the child table you'd have to make sure it's not the last one for its parent. (And in that case either forbid the delete or delete the parent with it.)
Forbid or react on updates to the IDs.
You can solve this by disabling (i.e. not granting) direct inserts and deletes (and maybe updates) on the table and provide PL/SQL functions to handle these instead.
If you are okay, however, with a 1:{0,1} or 1:{0,n} relation, then you can simply write the parent record and then look up its ID to write the child record(s).

inserting unique primary key exception

I was trying to insert records to a table using statement like
insert into table
(table_id, xxx,xxx)
values
(100,xxx,xxx)
and get the unique violation on the primary key.
and i did a select
select * from table where table_id = 100;
There is no record there.Thought insert before then, delete record.
And if i dont insert the table id, i got a null violation.
I was wondering if there is anyway to deal with this(maybe sequence)? I need to insert several thousands records using the inserting statement. some hundered have this prob.
Thanks in Advance!