What am I missing from this DELETE statement - sql-delete

Here is the question that I'am having problems with:
Write a DELETE statement that deletes the row in the Categories table that has an ID of 44444. When you execute this statement, it will produce an error since the category has related rows in the Products table. To fix that, precede the DELETE statement with another DELETE statement that deletes all products in this category.
I don't know why I keep getting this error message:
The DELETE statement conflicted with the REFERENCE constraint
"FK__Products__Catego__145C0A3F". The conflict occurred in database
"MyGuitarShop", table "dbo.Products", column 'CategoryID'.
And here is my SQL statement:
DELETE Categories
FROM Categories JOIN Products
ON Categories.CategoryID = Products.CategoryID
WHERE Categories.CategoryID = 44444;
I have been working on this for a while now and I can't figure out what im doing wrong and any help would be appreciated.

You have to delete the products first, then you will be able to delete the category. You have the error because of a foreign key constraint.
Therefore I would write 2 queries:
DELETE FROM Products WHERE CategoryID = 44444;
Now as there are no products with this id the category can be deleted:
DELETE FROM Categories WHERE CategoryID = 44444;

I know in Postgres at least you can use a cascade modifier to delete related rows.
DELETE FROM Categories WHERE CategoryID = 44444 CASCADE;

Related

How to delete from 2 tables that depend on each other in PostgreSQL?

I have a table with collection of objects, let's assume the table is called items. each item has some properties, and the id of the group into which it belongs.
items (id, name, created_at, group_id, ...)
For som reasons that I can't change, the item ids are first created and stored in a special table, and only then they are added to items table. So items.id has FK to item_ids.id.
item_ids (id, ..., ...)
Now I want to delete all the items of a given group. But if I delete them first from items table, I will lose their connection to the group and won't be able to delete them from item_ids table. Deleting item_ids first is also impossible, because doing so will violate the FK constraint and cause an error.
I don't want to use "in" because I'm afraid that there will be too many items to delete.
Is delete cascade my only option? Or is there another solution? How many ids can I safely put into an in clause?
I used the solution suggested by #Belayer, thank you!
First, change the FK constraint of the items table to be deferrable:
alter table items
ALTER CONSTRAINT item_id_fk DEFERRABLE INITIALLY immediate;
Then, in the transaction in which I delete the items, first set the constraint to be verified only at the end of the transaction (deferred), and then delete first the item_ids entries, and then the items entries:
begin;
set constraints item_id_fk deferred;
delete from item_ids using items where items.group_id in (...) and items.id = item_ids.id;
delete from items where group_id in (...);
commit;

Not able to delete value from a table that is associated with another with foreignkeyconstraint

Hi I have two table Customer and Orders.
Customer Id is primary in Customer and Foreign key in Orders.
I have done the following coding:
ForeignKeyConstraint custOrderFK = new ForeignKeyConstraint("CustOrderFK",
custDS.Tables["CustTable"].Columns["CustomerID"],
custDS.Tables["OrdersTable"].Columns["CustomerID"]);
custOrderFK.DeleteRule = Rule.None;
custDS.Tables["OrdersTable"].Constraints.Add(custOrderFK);
Since I have mentioned custOrderFK.DeleteRule = Rule.None; deleting an entry in customer's table should not affect order's table. But I am not able to delete a row from Customer table. It throws exception. I am new to ado.net.
Maybe something is wrong with my understanding of rules.
Use delete cascade option with foreign key.

how to delete row from join table with jpa 2

i have a relationship one to many that generated a join table , what i need to do is to delete a row from that join table, but i dont even know how to do the jpql query to get to that table because it's not an entity in my data model.
to give an idea of my issue :
i have the next tables:
user--- (one to many)---> permission, that generated the table user_permission.
i need to delete rows from user_permissions, because if i delete in permission all users with certain permission will lose it.
Delete the permission from the list of permissions of the user and then save the user object. If the cascade is configured correctly that should delete the respective entry from the join table.

Cascade new IDs to a second, related table

I have two tables, Contacts and Contacts_Detail. I am importing records into the Contacts table and need to run a SP to create a record in the Contacts_Detail table for each new record in the Contacts. There is an ID in the Contacts table and a matching ID_D in the Contacts_Detail table.
I'm using this to insert the record into Contacts_Detail but get the 'Subquery returned more than 1 value.' error and I can't figure out why. There are multiple records in Contacts that need have matching records in Contacts_Detail.
Insert into Contacts_Detail (ID_D)
select id from Contacts c
left join Contacts_Detail cd
on c.id = cd.id_d
where id_d is null
I'm open to a better way...
thanks.
It sounds like you're inserting blank child-records into your Contacts_Detail table -- so the first question I'd ask is: Why?
As for why your specific SQL isn't working...
A few things you can check:
Contacts table -- do you have any records there WHERE id is null?
(delete them -- then make the id field a primary key)
Contacts_Detail
table -- do you have any records there WHEERE id_d is null?
(delete them -- then go into your designer and create a relationship
/ enforce referential integrity.)
Verify that c.id is the primary
key, and cd.id_d is the correct foreign key to relate the tables.
Hope that helps
Why not just have a trigger? This seems a little simpler than having to determine for all time which rows are missing - that seems more like something you would do periodically to correct for some anomalies, not something you should have to do after every insert. Something like this should work:
CREATE TRIGGER dbo.NewContacts
ON dbo.Contacts
FOR INSERT
AS
BEGIN
INSERT dbo.Contacts_Detail(ID_D) SELECT ID FROM inserted;
END
GO
But I suspect you have a trigger on the Contacts_Detail table that is not written to correctly handle multi-row inserts, and that's where your subquery error is coming from. Can you show the trigger on Contacts_Detail?

SQL Server Trigger to DELETE one record from multiple tables

I know this can be done with foreign keys but I cannot add them or something weird happens when I am inserting new records. There are a lot of stored procedures in this database and I don't know what they do since I know nothing about stored procedures. I was hoping someone could help me figure out a trigger that will delete a specific ProductID when I delete it from the Product table. It is also located in tables called CompanyLink, TargetLink, and CategoryLink.
As of right now, when I delete the ProductID from the Product table, I have to manually delete it from the other 3 tables it was inserted into.
You can do it through a trigger like this:
CREATE TRIGGER [dbo].[ProductDeleted]
ON [dbo].[Product]
AFTER DELETE
AS
BEGIN
DELETE FROM CompanyLink WHERE ProductID = (SELECT TOP 1 ProductID FROM DELETED)
DELETE FROM TargetLink WHERE ProductID = (SELECT TOP 1 ProductID FROM DELETED)
END
Obviously the syntax might not be perfect, but this is close to what you need.