Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NOT EXISTS with COMPOSITE KEYS in SQL for inserting data from POJO

I am using DB2 DBMS.

Scenario 1:

myTable has a composite key (key1, key2) where both key1 and key2 are foreign keys from yourTable.

I want to insert new data from yourTable into myTable, but only if the key1, key2 combination does not already exist in myTable.

insert into myTable(key1, key2, someData)
values(x, y, z)
where NOT EXISTS (want to check if composite key is not already present)

Scenario 2:

I put data into a java object from yourTable with properties data1, data2, and data.

I want to insert the above data with the check as in Scenario1. data1 + data2 should not already be present in myTable.

How do I achieve this? I don't think we can use a SELECT statement inside the insert statement.

insert into myTable(key1, key2, data)
values(data1, data2, data)
where (data1 + data2 are already not present in myTable)

How can I achieve this?

like image 385
Vicky Avatar asked Aug 22 '11 12:08

Vicky


People also ask

How do you write a composite key in SQL?

Using database: USE School; Creating table with a composite key: CREATE TABLE student (rollNumber INT, name VARCHAR(30), class VARCHAR(30), section VARCHAR(1), mobile VARCHAR(10), PRIMARY KEY (rollNumber, mobile));

Can composite primary key be null in SQL Server?

In composite primary key columns you cannot pass null values. Each column defined as a primary key would be validated so that null values are not passed on to them. If you have given a Unique constraint then we have a chance of NULL values being accepted. But in case of primary keys they cannot hold null values.

How do I create a composite unique key in SQL Server?

You can also create a Composite Unique Key consisting of two or more fields. To do that we need to apply the Unique Constraint on the table level. In the following example, we create a unique key consisting of FirstName & LastName . The FirstName & LastName themselves can contain duplicate values.

What is an example of a composite key in a database table?

In a table representing students our primary key would now be firstName + lastName. Because students can have the same firstNames or the same lastNames these attributes are not simple keys. The primary key firstName + lastName for students is a composite key.


1 Answers

insert into mytable(...)
select ...
from yourtable y
left join mytable m
on y.key1 = m.key1 and y.key2 = m.key2
where m.key is null

or

insert into mytable(...)
select ...
from yourtable y
where not exists (select 1 from mytable m where y.key1 = m.key1 and y.key2 = m.key2)

for your 2nd scenario, it'd look similar to the above query

insert into mytable(...)
select ...
where not exists (select 1 from mytable m where javakey1 = m.key1 and javakey2 = m.key2)
like image 199
Derek Kromm Avatar answered Sep 26 '22 15:09

Derek Kromm