INSERT statement conflicted with the FOREIGN KEY constraint even after deleting the records from the child table - sql

I tired to delete the occurrences of the values which the insert stmt was trying to insert
in the dependent table.
delete from BSC_UR_RE_AN
where AN_ID in (1084,1083,1088,1087,1121,1122,1123,1094,5010,
1239,1242,70187,7001,7002,1284,1285)
But no luck, I got the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint
"BSC_U_RA_AN_FK". The conflict occurred in database "DMDB", table
"dbo.BSC_AN", column 'AN_ID'.

That error means that ANAG_ID value you're trying to insert as FOREIGN KEY doesn't exists on the related table. So, you should not delete it, you should insert it if it's missing.
Edit:
You should have a clear view of your tables design, examining the constraint of the tables you're trying to insert into.
As example, a Foreign Key constraint usually refers to a Primary Key of another table.
The error you see is because you're trying to inserd an invalid value (eg. not exists in the master table).
An example:
CREATE TABLE MasterTable (
ID int NOT NULL PRIMARY KEY,
Name varchar(50)
)
CREATE TABLE MasterTableValues (
IDMasterTable INT REFERENCES MasterTable(ID), --FOREIGN KEY
Value varchar(50)
)
Let's assume you have this data in MasterTable:
1 FirstDate
2 SecondData
3 ThirdData
5 FifthData
Now, you can insert these values in MasterTableValues:
1 SomeValue
1 SomeOtherValue
3 SomeValue
But CANNOT insert this value:
4 SomeValue
because the key ID = 4 don't exist in MasterTable

Related

No auto increment in my foreign key

I'm working in my school project and I want to make the id subject of any student incremented automatically as foreign key. I am showing you the example below as prototype, there are two tables, when I'm trying to insert data into the second table, I get an error (necessary to insert another field id of the table)
CREATE DATABASE database1;
USE database1;
CREATE TABLE table1
(
IdTable1 INT NOT NULL IDENTITY,
NOM VARCHAR(30),
PRIMARY KEY(IDMEDO)
);
--auto increment is working here
INSERT INTO table1
VALUES ('data1Table1'), ('data2Table1'), ('data3Table1');
--auto increment is working here just with the primary key
CREATE TABLE table2
(
IdTable2 INT not null IDENTITY,
IdTable1 INT,
dataTable2 varchar(30),
primary key(IdTable2),
constraint fk_tbl1 foreign key(IdTable1) references Table1
);
--necessary to add id field
INSERT INTO table2
VALUES ('data1Table2'), ('data2Table2'), ('data3Table2');
You should always (as a "best practice") define the columns you want to insert data into - that way, you can specify those that you have to provide values for, and let SQL Server handle the others. And for the foreign key, you have to explicitly provide a value - there's no "auto-magic" (or "auto-incrementing") way of associating a child row with its parent table - you have to provide the value in your INSERT statement.
So change your code to:
-- explicitly *specify* the NOM column here!
INSERT INTO table1 (NOM)
VALUES ('data1Table1'), ('data2Table1'), ('data3Table1');
-- again: explicitly *specify* the columns you want to insert into!
INSERT INTO table2 (IdTable1, dataTable2)
VALUES (1, 'data1Table2'), (2, 'data2Table2'), (3, 'data3Table2');
You need to insert the value of the foreign key wrt to table 1 now if you enter a value that's not in table 1 column which is acting as a foreign key then also it will not accept
Simply
Primary key and foreign key should match
Foreign key can't be null if table 1 doesn't contain a primary key with value null

SQL trigger INSERT AFTER

I am trying to setup a trigger in phpMyAdmin. have two tables, one parent, one child. Every time a new user in users is created I want to automaticly create a line in the permissions table with the (AI) generated id from users as user_id. (permissions.user_id is a foreigh key of users.id)
users:
id email password
--------------------------------------
1 eric#test.com sdgsdhdfhs
2 john#test.com dfgsdgdfhg
3 mary#test.com plkdfjvjvv
permissions:
index user_id allow_read allow_write allow_delete
-------------------------------------------------------------
1 1 1 0 1
2 2 1 1 1
3 3 0 0 0
I've tried (without success):
INSERT
INTO permissions
(user_id)
VALUES
(IDENT_CURRENT('users'))
and
INSERT
INTO permissions
(user_id)
VALUES
(##IDENTITY)
To access the data of the row that caused a trigger to be executed, you can use NEW and OLD aliases. For INSERT triggers only NEW is available. For DELETE triggers only OLD is available. In UPDATE triggers you can use both. They are used the same way as table aliases (e.g. NEW.id / OLD.id).
Given a parent and a child table as follows:
create table parent_table(
id int auto_increment primary key,
pdata varchar(50)
);
create table child_table(
id int auto_increment primary key,
parent_id int not null,
cdata varchar(50) default '',
foreign key (parent_id) references parent_table(id)
);
To insert a child row when a parent row is inserted:
create trigger insert_parent
after insert on parent_table
for each row
insert into child_table(parent_id)
values (new.id);
To delete all related child rows wehen a parent row is deleted:
create trigger delete_parent
before delete on parent_table
for each row
delete from child_table
where parent_id = old.id;
Demo: http://rextester.com/EOW74217
However a delete trigger is not necessary if you define your foreign key with ON DELETE CASCADE
foreign key (parent_id) references parent_table(id) on delete cascade
All related child rows will be deleted without a trigger when you delete the parent row.
Demo: http://rextester.com/CWB43482

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

Why does add a foreign key to the tblDomare table result in this error?
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__tblDomare__PersN__5F7E2DAC". The conflict occurred in database "almu0004", table "dbo.tblBana", column 'BanNR'.
Code
CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
PRIMARY KEY (PersNR));
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (7606091347,'Josefin','Backman',4);
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (8508284163,'Johanna','Backman',1);
CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL,
PRIMARY KEY (BanNR));
INSERT INTO tblBana (BanNR)
Values (1);
INSERT INTO tblBana (BanNR)
Values (2);
INSERT INTO tblBana (BanNR)
Values (3);
ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
It occurred because you tried to create a foreign key from tblDomare.PersNR to tblBana.BanNR but/and the values in tblDomare.PersNR didn't match with any of the values in tblBana.BanNR. You cannot create a relation which violates referential integrity.
This query was very useful for me. It shows all values that don't have any matches
select FK_column from FK_table
WHERE FK_column NOT IN
(SELECT PK_column from PK_table)
Try this solution:
There is a data item in your table whose associated value doesn't exist in the table you want to use it as a primary key table.
Make your table empty or add the associated value to the second table.
It is possible to create the foreign key using ALTER TABLE tablename WITH NOCHECK ..., which will allow data that violates the foreign key.
"ALTER TABLE tablename WITH NOCHECK ..." option to add the FK -- This solution worked for me.
Remove all existing data from your tables and then make a relation between the tables.
Before You add Foreign key to the table, do the following
Make sure the table must empty or The column data should match.
Make sure it is not null.
If the table contains do not go to design and change, do it manually.
alter table Table 1 add foreign key (Column Name) references Table 2 (Column Name)
alter table Table 1 alter column Column Name attribute not null
I guess, a column value in a foreign key table should match with the column value of the primary key table. If we are trying to create a foreign key constraint between two tables where the value inside one column(going to be the foreign key) is different from the column value of the primary key table then it will throw the message.
So it is always recommended to insert only those values in the Foreign key column which are present in the Primary key table column.
For ex. If the Primary table column has values 1, 2, 3 and in Foreign key column the values inserted are different, then the query would not be executed as it expects the values to be between 1 & 3.
In very simple words your table already has data present in it and the table you are trying to create relationship with does have that Primary key set for the values that are already present.
Either delete all the values of the existing table.
Add all the values of foreign key reference in the new table.
Try DELETE the current datas from tblDomare.PersNR . Because the values in tblDomare.PersNR didn't match with any of the values in tblBana.BanNR.
When you define a Foreign Key in table B referencing the Primary Key of table A it means that when a value is in B, it must be in A. This is to prevent unconsistent modifications to the tables.
In your example, your tables contain:
tblDomare with PRIMARY KEY (PersNR):
PersNR |fNamn |eNamn |Erfarenhet
-----------|----------|-----------|----------
6811034679 |'Bengt' |'Carlberg' |10
7606091347 |'Josefin' |'Backman' |4
8508284163 |'Johanna' |'Backman' |1
---------------------------------------------
tblBana:
BanNR
-----
1
2
3
-----
This statement:
ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
says that any line in tblDomare with key PersNR must have a correspondence in table tblBana on key BanNR. Your error is because you have lines inserted in tblDomare with no correspondence in tblBana.
2 solutions to fix your issue:
either add lines in tblBana with BanNR in (6811034679, 7606091347, 8508284163)
or remove all lines in tblDomare that have no correspondence in tblBana (but your table would be empty)
General advice: you should have the Foreign Key constraint before populating the tables. Foreign keys are here to prevent the user of the table from filling the tables with inconsistencies.
i had this error too
as Smutje reffered make sure that you have not a value in foreign key column of your base foreign key table that is not in your reference table i.e(every value in your base foreign key table(value of a column that is foreign key) must also be in your reference table column)
its good to empty your base foreign key table first then set foreign keys
the data you have entered a table(tbldomare) aren't match a data you have assigned primary key table. write between tbldomare and add this word (with nocheck) then execute your code.
for example you entered a table tbldomar this data
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);
and you assigned a foreign key table to accept only 1,2,3.
you have two solutions one is delete the data you have entered a table then execute the code. another is write this word (with nocheck) put it between your table name and add
like this
ALTER TABLE tblDomare with nocheck
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
Smutje is correct and Chad HedgeCock offered a great layman's example.
Id like to build on Chad's example by offering a way to find/delete those records.
We will use Customer as the Parent and Order as the child. CustomerId is the common field.
select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null
if you are reading this thread... you will get results. These are orphaned children. select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null Note the row count in the bottom right.
Go verify w/ whomever you need to that you are going to delete these rows!
begin tran
delete Order
from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null
Run the first bit.
Check that row count = what you expected
commit the tran
commit tran
Be careful. Someone's sloppy programming got you into this mess. Make sure you understand the why before you delete the orphans. Maybe the parent needs to be restored.
From our end, this is the scenario:
We have an existing table in the database with records.
Then I introduces a NOT nullable foreign key
After executing the update i got this error.
How did i solve you ask?
SOLUTION: I just removed all the records of the table, then tried to update the database and it was successful.
This happens to me, since I am designing my database, I notice that I change my seed on my main table, now the relational table has no foreign key on the main table.
So I need to truncate both tables, and it now works!
You should see if your tables has any data on the rows. If "yes" then you should truncate the table(s) or else you can make them to have the same number of data at tblDomare.PersNR to tblBana.BanNR and vise-verse.
In my scenario, using EF, upon trying to create this new Foreign Key on existing data, I was wrongly trying to populate the data (make the links) AFTER creating the foreign key.
The fix is to populate your data before creating the foreign key since it checks all of them to see if the links are indeed valid. So it couldn't possibly work if you haven't populated it yet.
I encounter some issue in my project.
In child table, there isn't any record Id equals 1 and 11
I inserted DEAL_ITEM_THIRD_PARTY_PO table which Id equals 1 and 11 then I can create FK
Please first delete data from that table and then run the migration again. You will get success
I had the same problem.
My issue was having nullable: true in column (migration file):
AddColumn("dbo.table", "column", c => c.Int(nullable: true));
Possible Solutions:
Change nullable 'false' to 'true'. (Not Recommended)
Change property type from int to int? (Recommended)
And if required, change this later after adding column > then missing field data in previous records
If you've changed an existing property from nullable to non-nullable:
3) Fill the column data in database records
A foreign key constraint in a child table must have a parent table with a primary key. The primary key must be unique. The foreign key value must match a value in the patent table primary key
When you alter table column from nullable to not nullable column where this column is foreign key, you must :
Firstly, initialize this column with value (because it is foreign
key not nullable).
After that you can alter your table column normally.
Please try below query:
CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL PRIMARY KEY,
);
CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL PRIMARY KEY,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
FK_tblBana_Id VARCHAR (15) references tblBana (BanNR)
);
INSERT INTO tblBana (BanNR)
Values (3);
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet,FK_tblBana_Id)
Values (8508284173,'Johanna','Backman',1,3);
or you can use this
SELECT fk_id FROM dbo.tableA
Except
SELECT fk_id From dbo.tableB
and just FYI, in case you do all of your data reference checks and find no bad data...apparently it is not possible to create a foreign key constraint between two tables and fields where those fields are the primary key in both tables! Do not ask me how I know this.

PostgreSQL delete fails with ON DELETE rule on inherited table

In my PostgreSQL 9.1 database I've defined RULEs that delete rows from child tables whenever a parent table row is deleted. This all worked OK, until I introduced inheritance. If the parent (referencing) table INHERITS from another table and I delete from the base table then the DELETE succeeds, but the RULE doesn't appear to fire at all - the referenced row is not deleted. If I try to delete from the derived table I get an error:
update or delete on table "referenced" violates foreign key constraint "fk_derived_referenced" on table "derived"
There is no other row in the parent table that would violate the foreign key: it's being referenced by the row that's being deleted! How do I fix this?
The following script reproduces the problem:
-- Schema
CREATE TABLE base
(
id serial NOT NULL,
name character varying(100),
CONSTRAINT pk_base PRIMARY KEY (id)
);
CREATE TABLE referenced
(
id serial NOT NULL,
value character varying(100),
CONSTRAINT pk_referenced PRIMARY KEY (id)
);
CREATE TABLE derived
(
referenced_id integer,
CONSTRAINT pk_derived PRIMARY KEY (id),
CONSTRAINT fk_derived_referenced FOREIGN KEY (referenced_id) REFERENCES referenced (id)
)
INHERITS (base);
-- The rule
CREATE OR REPLACE RULE rl_derived_delete_referenced
AS ON DELETE TO derived DO ALSO
DELETE FROM referenced r WHERE r.id = old.referenced_id;
-- Some test data
INSERT INTO referenced (id, value)
VALUES (1, 'referenced 1');
INSERT INTO derived (id, name, referenced_id)
VALUES (2, 'derived 2', 1);
-- Delete from base - deletes the "base" and "derived" rows, but not "referenced"
--DELETE FROM base
--WHERE id = 2;
-- Delete from derived - fails with:
-- update or delete on table "referenced" violates foreign key constraint "fk_derived_referenced" on table "derived"
DELETE FROM derived
WHERE id = 2
As I said in my comment, this seems an unusual way to do things. But you can make it work with a deferred constraint.
CREATE TABLE derived
(
referenced_id integer,
CONSTRAINT pk_derived PRIMARY KEY (id),
CONSTRAINT fk_derived_referenced FOREIGN KEY (referenced_id)
REFERENCES referenced (id) DEFERRABLE INITIALLY DEFERRED
)
INHERITS (base);
The PostgreSQL docs, Rules vs. Triggers, say
Many things that can be done using triggers can also be implemented
using the PostgreSQL rule system. One of the things that cannot be
implemented by rules are some kinds of constraints, especially foreign
keys.
But it's not clear to me that this specific limitation is what you're running into.
Also, you need to check if other records are still referencing the to-be-deleted rows. I added a test derived record#3, which points to the same #1 reference record.
-- The rule
CREATE OR REPLACE RULE rl_derived_delete_referenced
AS ON DELETE TO tmp.derived DO ALSO (
DELETE FROM tmp.referenced re_del
WHERE re_del.id = OLD.referenced_id
AND NOT EXISTS ( SELECT * FROM tmp.derived other
WHERE other.referenced_id = re_del.id
AND other.id <> OLD.id )
;
);
-- Some test data
INSERT INTO tmp.referenced (id, value)
VALUES (1, 'referenced 1');
-- EXPLAIN ANALYZE
INSERT INTO tmp.derived (id, name, referenced_id)
VALUES (2, 'derived 2', 1);
INSERT INTO tmp.derived (id, name, referenced_id)
VALUES (3, 'derived 3', 1);
-- Delete from base - deletes the "base" and "derived" rows, but not "referenced"
--DELETE FROM base
--WHERE id = 2;
-- Delete from derived - fails with:
-- update or delete on table "referenced" violates foreign key constraint "fk_derived_referenced" on table "derived"
EXPLAIN ANALYZE
DELETE FROM tmp.derived
WHERE id = 2
;
SELECT * FROM tmp.base;
SELECT * FROM tmp.derived;
SELECT * FROM tmp.referenced;

Using references in MYSQL

I got an answer to another question here:
DB Schema For Chats?
It's a great answer, but I am not understanding the bit about references. I can do SQL statements but I have never used references.
What are they used for?
How are they used?
Give an example please
The REFERENCES keyword is part of a foreign key constraint and it causes MySQL to require that the value(s) in the specified column(s) of the referencing table are also present in the specified column(s) of the referenced table.
This prevents foreign keys from referencing ids that do not exist or were deleted, and it can optionally prevent you from deleting rows whilst they are still referenced.
A specific example is if every employee must belong to a department then you can add a foreign key constraint from employee.departmentid referencing department.id.
Run the following code to create two test tables tablea and tableb where the column a_id in tableb references the primary key of tablea. tablea is populated with a few rows.
CREATE TABLE tablea (
id INT PRIMARY KEY,
foo VARCHAR(100) NOT NULL
) Engine = InnoDB;
INSERT INTO tablea (id, foo) VALUES
(1, 'foo1'),
(2, 'foo2'),
(3, 'foo3');
CREATE TABLE tableb (
id INT PRIMARY KEY,
a_id INT NOT NULL,
bar VARCHAR(100) NOT NULL,
FOREIGN KEY fk_b_a_id (a_id) REFERENCES tablea (id)
) Engine = InnoDB;
Now try these commands:
INSERT INTO tableb (id, a_id, bar) VALUES (1, 2, 'bar1');
-- succeeds because there is a row in tablea with id 2
INSERT INTO tableb (id, a_id, bar) VALUES (2, 4, 'bar2');
-- fails because there is not a row in tablea with id 4
DELETE FROM tablea WHERE id = 1;
-- succeeds because there is no row in tableb which references this row
DELETE FROM tablea WHERE id = 2;
-- fails because there is a row in tableb which references this row
Important note: Both tables must be InnoDB tables or the constraint is ignored.
The REFERENCES keyword shows a foreign key constraint, which means that:
FOREIGN KEY (`chat_id` ) REFERENCES `chats`.`chat` (`id` )
...the chat_id column in the current table can only contain values that already exist in the chat table, id column.
For example, if the CHAT.id column contains:
id
----
a
b
c
..you can not add any values other than a/b/c into the chat_id column.