How to prevent inserting duplicate rows based on two foreign keys? - sql

If I am manually inserting hundreds of rows, how should I efficiently write the insert statements so that each insert will not run only if both foreign keys are already present together in a record in that database?

Create a constraint on the columns, here is a great reference starting point.
Here is an example of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)

You can add a unique constraint as described by #BrianAtkins and you can also use a MERGE statement instead of INSERT in order to avoid breaking the entire insert on a unique constraint violation.

Related

Create a table in SQL where the Composite Primary Key is also a Foreign Key

I need to create a table called LFM_Enroll in SQL that has a composite primary key of Student_ID and Section_Number. Student_ID is also a foreign key, it references Student_ID in the LFM_Student table and Section_Number is also a foreign key, it references Section_Number in the LFM_Section table. How do I write the constraints and foreign keys? I've attached an image of the tables and below is what I have done so far. After the LFM_Enroll table is created I need to update one row. I tried doing so but kept getting the below error.
: Error starting at line : 173 in command -
UPDATE LFM_Enroll
SET Student_ID = 1234567,
Section_Number = 01234
WHERE Student_ID = 900000 AND Section_Number = 4138
Error report -
ORA-02291: integrity constraint (SYSTEM.FK_LFM_ENROLL_SECTION_NUMBER) violated - parent key not found.
Tables Thanks in advance for all your help.
CREATE TABLE LFM_Enroll (
Student_ID char(7),
Section_Number char(4),
constraint PK_LFM_Enroll Primary Key (Student_ID,Section_Number),
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID,Section_Number) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Student_ID,Section_Number) references LFM_Section (Section_Number)
);
Your foreign key constraints are not right. You are trying to map two columns {Student_ID,Section_Number} to a single column LFM_Student.Student_ID.
The number of columns in the principal key must match the number of columns in the foreign key. In other words, the key LFM_Student is one column (Student_ID), so the foreign key also needs to be a single matching column - in this case LFM_Enroll.Student_ID. Correct DDL would be:
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Section_Number) references LFM_Section (Section_Number)
I'm not quite sure why your RDBMS is allowing what you have, but it may be using the first column and simply ignoring the second. In which case FK_LFM_Enroll_Section_Number is creating a foreign key LFM_Enroll.Student_ID => LFM_Section.Section_Number.
The error indicates that the values with which you are trying to update the two columns may not exist in Student and / or Sections tables i.e. 1234567 doesn't exists in the student table and / or 01234 doesn't exist in your section table . You should try inserting new rows or updating existing ones with the new values you are trying to update your foreign keys with.
[Edit: For defining constraints refer lc.'s post]

How to add foreign key to an existing column in SQL Server 2012

I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.
Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);
CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

SQL-Using unique constraints to remove duplicate entries from being entered in a table

I have a sql statement and I am trying to add a unique constraint that prevents an duplicate entry from being entered twice in the table. Can anyone help me out with my code if I am writing it correctly?
CREATE TABLE GroupMembership
(GroupID INT REFERENCES dbo.Groups (GroupID),
IndividualID INT NOT NULL REFERENCES dbo.Individuals (IndividualID) PRIMARY KEY(GroupID, IndividualID),
CONSTRAINT AK_IndividualID UNIQUE IndividualID);
I tried to test it via SQL server but it is giving me an error.
You are missing a couple of things:
A comma after the IndividualId column specification (as the primary key does not relate to it - it's a multiple-column constraint)
Brackets around the IndividualId column in the unique constraint specification.
So:
CREATE TABLE GroupMembership
(GroupID INT REFERENCES dbo.Groups (GroupID),
IndividualID INT NOT NULL REFERENCES dbo.Individuals (IndividualID),
PRIMARY KEY(GroupID, IndividualID),
CONSTRAINT AK_IndividualID UNIQUE (IndividualID)
);

How to add composite primary key to table

create table d(id numeric(1), code varchar(2))
After I create the above table how can I add a composite primary key on both fields and also a foreign key?
In Oracle, you could do this:
create table D (
ID numeric(1),
CODE varchar(2),
constraint PK_D primary key (ID, CODE)
);
alter table d add constraint pkc_Name primary key (id, code)
should do it. There's lots of options to a basic primary key/index depending on what DB your working with.
The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.
You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:
This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.
CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)
If you don't have a table that we can reference, add one like this so that the example will work:
CREATE TABLE Codes (
Code [varchar](2) PRIMARY KEY
)
NOTE: you must have a table to reference before creating the foreign key.
If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

Suggestions for insert with Foreign key constraint in mysql

I have a table containing 2 entries.
Something like
CREATE TABLE `db`.`main` (
`id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
);
The id for these 2 entries are automatically generated primary keys.
I have another table with a rule linking
CREATE TABLE `db`.`day` (
`main_id` int(10) unsigned NOT NULL,
`day` tinyint(4) NOT NULL,
CONSTRAINT `fk_db_main` FOREIGN KEY (`main_id`) REFERENCES `main` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
);
now I can successfully get a result using
SELECT * FROM main where id='9';
but when I try to run
INSERT INTO day (main_id, day) VALUES (9, 0);
I get
"Cannot add or update a child row: a foreign key constraint fails (db.day, CONSTRAINT fk_db_main FOREIGN KEY (main_id) REFERENCES main (id) ON DELETE NO ACTION ON UPDATE NO ACTION) (1452)"
Any suggestions on what I am missing with the insert?
**I hadn't listed the actual cause of the issue while asking the question. The actual cause was that the main db table was in MyISAM, and the InnoDB tables couldn't create a foreign key connecting to it. In short, MyISAM doesn't support foreign keys, even when they are coming from other tables.
The insert works for me if I remove the db. parts in the CREATE TABLE statements (and insert into main a row with an id of 9). Maybe the problem is that you're using that db. prefix inconsistently, i.e. after TABLE but not in the CONSTRAINT clause...?
The FOREIGN KEY constraint says "there shall be an entry in the 'main` table with an ID value that matches the newly inserted 'main_id' value in the 'day' table".
When you INSERT the value 9 into 'day', is there already a row in 'main' with ID = 9?
The DBMS doesn't think so - that's why it complained.
I hadn't listed the actual cause of the issue while asking the question. The actual cause was that the main db table was in MyISAM, and the InnoDB tables couldn't create a foreign key connecting to it. In short, MyISAM doesn't support foreign keys, even when they are coming from other tables.