Delete based on primary key from associative table - Error - sql

I'm trying to delete 1 record based on primary key from (3) tables.
Here is the statement that I'm using
DELETE FROM CUSTOMER
WHERE EXISTS
( SELECT MERCHANTNAME
FROM CREDITCARD
WHERE MERCHANTNAME = 'VISA');
Deleting record of a customer with a VISA from customer table.
Here is the error that I'm getting
ORA-02292: integrity constraint
(PLATINUMAUTOGROUP.CDRIVERLICENSENUM_FK) violated - child record found
I'm guessing CDRIVERLICENSENUM is the foreign key in the 3rd table that I have. How do I go about this? Is it possible to delete 1 record from 3 tables in 1 statement?
the three tables are
customer / customer_creditcard / creditcard

You need to delete the records in the foreing tables before deleting the record in the primary table.
But perhaps your delete command in the CUSTOMER table might be wrong, because if the EXISTS command return true, all records will be deleted from the CUSTOMER table. Check if this is the result you expect.

Related

Performing SQL Query to Remove Unused Users from a Database

I'm currently working with a database that consists of a users table, a permissions table, a set of documents-related tables, and several miscellaneous tables that have foreign key dependencies on rows in the user table.
I'm trying to remove all user entries from the 'Users' table that meet the following criteria:
Not referenced by an entry in one of the documents tables.
Not referenced by an entry in the permissions table.
Contains a null value in the 'Customer ID' column of the User row.
I'm able to create a query that gets all users, which looks like this:
SELECT id
INTO MyTableVar
FROM Users
WHERE
(NOT EXISTS (SELECT Author_Id FROM ItemInstances_DocumentInstance
WHERE Users.Id = ItemInstances_DocumentInstance.Author_Id)
AND NOT EXISTS (SELECT CompletedBy_Id FROM TaskInstanceUser
WHERE Users.Id = TaskInstanceUser.CompletedBy_Id)
AND Cust_Id IS NULL
AND Id > 4)
SELECT *
FROM MyTableVar
This query gets all of Id's of users that I want to remove, but I get an error when I try to delete these entries
The DELETE statement conflicted with the REFERENCE constraint "FK_MessageUser_User.
I'm stumped as to how I should use the ID's I've queried to remove entries in the MessageUser_User table that correspond to users I want to delete. I feel like this should be easy, but I can't figure out a way to do it with SQL syntax.
PS: I'd also appreciate some feedback on how I wrote what I have so far for my query. I'd love to know what I could do to make it cleaner. I'm new to SQL and need all the help I can get.
I'm guessing that the table with the Foreign Key does not have ON DELETE CASCADE which you can read about here.
If you have the ability to alter constraints on your table, you can do this, which will permit the referencing table to automatically delete records that reference a deleted row from the main table.
ALTER TABLE MessageUser_User DROP
CONSTRAINT FK_MessageUser_User;
ALTER TABLE MessageUser_User ADD
CONSTRAINT FK_MessageUser_User
FOREIGN KEY (<<IdColumnName>>)
REFERENCES Users (Id)
ON DELETE CASCADE;
Otherwise, you can use a separate query to delete from MessageUser_User where it contains the IDs you want to delete in it's foreign key column:
DELETE FROM MessageUser_User WHERE ID IN (SELECT ID FROM MyTableVar );
Regarding the style of your delete query - I usually prefer to do left joins then delete the records where there is a null in the right table(s):
SELECT id
INTO MyTableVar
FROM Users
LEFT JOIN ItemInstances_DocumentInstance ON Author_Id = Users.Id
LEFT JOIN TastInstanceUser ON CompletedBy_Id = Users.Id
WHERE
Author_Id IS NULL
AND CompletedBy_Id IS NULL
AND Cust_Id IS NULL
AND Id > 4

Delete record where from multi table when it doesn't exist in table

I have 3 tables.
mainT has primary key main_id
sub1T has foreign key to main_id
sub2T has foreign key to main_id
I need to delete all records from sub1T and sub2T in one SQL command.
I know how to delete all records inside sub1T using this command:
DELETE FROM `sub1T`
WHERE NOT EXISTS (SELECT NULL
FROM mainT
WHERE `mainT`.main_id = main_id)
I need to delete from multiple child tables

How can this SQL statement throw the following exception?

how can this statement:
DELETE FROM passage
WHERE passageid NOT IN
(
SELECT passageid from PreEndedPassages_passages
UNION SELECT fromPassageid from severalvisit
UNION SELECT toPassageid from severalvisit
UNION SELECT registerPassageid from stationobjects WHERE registerpassageid IS NOT NULL
UNION SELECT beginPassageid from stationobjects WHERE beginPassageid IS NOT NULL
UNION SELECT endPassageid from stationobjects WHERE endPassageid IS NOT NULL
)
throw this exception?
The DELETE statement conflicted with the FOREIGN KEY constraint "FK_statobj_begpasid". The conflict occurred in database "db.mdf", table "dbo.stationobjects", column 'beginpassageid'.
I have no clue, but it happened. beginPassageId is a foreign key on passageid.
EDIT:
Consider the NOT IN. I want to delete all passages that don't exist in one of its related tables. It usually works, but it happened once.
Thank you.
It means passage is parent table. and stationobjects is child table. You are trying to remove passageid from passage table which is present in stationobjects table as well.
First try to remove those passageid from stationobjects and then you can run this delete statement.
Alternate approach is cascade delete, if your DB supports that.
this kind of occur when you have a foreign key relationship in the two table.
This violates the Refrential Integrity .
so if you delete record from the primary table and record exist in foreign key table,
then you have two options:
1. either set the delete rule to cascade so that when ever you delete primary record the foreign key table record will get automatically deleted.
2.delete record from foreign key table first then from primary key table.
These kind of errors come up when table A foreign key is table B primary key and when you try to delete record in table A that has linking in table B, then deletion will not happen. Try dropping foreign key relation before delete. Same way truncate is used in tables by dropping fk relations and rebuilding them again after the table is reset

Deleted foreign key reference, still get error when deleting

I have a web app that calls an sql script that is trying to delete a row from table_1. However, table_2 references it with an FK constraint, so this was giving an error. I manually deleted the referencing row of table_2. (I confirmed via query that it's gone.) Then I ran the app and I still get the same error! (The DELETE statement conflicted with the REFERENCE constraint "table_2_fk". The conflict occurred in database "my_db", table "table_2", column 'table_1_pk'.
Why?
Table info
table_2 has columns pk, name, and table_1_pk. It has an FK constraint table_2_fk that ensures that table_1_fk = table_1.pk
table_1 has pk, a bunch of other columns, and no FK constraint.
details of delete and query
Suppose that table_1.pk = 1. I ran the statement
delete from table_2 where table_1_pk = 1
I then queried the db:
select * from table_2 where table_1_pk = 1
This returned 0 results.
You should change your code so that you delete from table 2 first, then delete from table 1. Or optionally add a Cascade delete to you foreign key constraint (automatically deletes from table 2 when a delete is made in table 1)
ADD CONSTRAINT [FK_Table2_table1] FOREIGN KEY([table_1_pk])
REFERENCES [dbo].[table1] ([table_1_fk ])
ON DELETE CASCADE

foreign key: conflicted with foreign key constraint

so i have 2 tables related to each other with an fk
appointment
{id, dept.id, datetime, sometable.id, sometableagain.id}
task
{id, appointment.id, deptlead.id, taskname}
deptlead
{id, name}
so i had to alter the appointment table to another foreignkey from another table. so i dropped the keys (task_appointment_fk, appointment_sometable_fk, appointment_sometableagain_fk) altered the table to add the new field and added again everything. the last two got added with no problems. while the other one (task_appointment_fk) kept giving me a this message :
"ALTER TABLE statement conflicted with the Forien Key Constraint "dept_appointment". The Cconflict occurred in the database "MyDb" , table "appointment", column "id"
so i found some solutions that states that there might be some rows on the task that has a appointmentid value that does not exist on the appointment table. so i tried inserting rows that would have the same value right. still gives me the same thing. the thing is , i want to delete the rows from the task to make it easier but doing that i have to drop all the fks again and do the same thing all over on the other tables, and i have a lot of other tables..
need some advice.
thanks!!
You can write a query to see which values in foreign key table does not have a matching key record in primary key table .If values are there then try to delete them .
select * from [task] a
left join [appointment] b
on a.appointment_id = b.id