views:

219

answers:

6

I have a row in a table. This row has an ID column referenced in a few other tables with millions of rows. The SQL statement to delete the row always times out. From my design, I know the row I wish to delete is never referenced any where else. Hence I would like SQL to ignore having to check all other tables for a foreign key reference to this row and delete the row immediately. Is there a quick way to do this in SQL 2008? Perhaps something along the lines of:

DELETE FROM myTable where myTable.ID = 6850 IGNORE CONSTRAINTS

Or something along those lines.

+4  A: 

You can set the constraints on that table / column to not check temporarily, then re-enable the constraints. General form would be:

ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName

Then re-enable all constraints with

ALTER TABLE TableName CHECK CONSTRAINT ConstraintName

I assume that this would be temporary though? You obviously wouldn't want to do this consistently.

Jeff
+1  A: 

You could maybe disable and re-enable constraints:

http://sqlforums.windowsitpro.com/web/forum/messageview.aspx?catid=60&threadid=48410&enterthread=y

davek
+1  A: 

On all tables with foreign keys pointing to this one, use:

ALTER TABLE MyOtherTable NOCHECK CONSTRAINT fk_name
Damir Sudarevic
+2  A: 

Yes, simply run

DELETE FROM myTable where myTable.ID = 6850

AND LET ENGINE VERIFY THE CONSTRAINTS.

If you're trying to be 'clever' and disable constraints, you'll pay a huge price: enabling back the constraints has to verify every row instead of the one you just deleted. There are internal flags SQL keeps to know that a constraint is 'trusted' or not. You're 'optimization' would result in either changing these flags to 'false' (meaning SQL no longer trusts the constraints) or it has to re-verify them from scratch.

See Guidelines for Disabling Indexes and Constraints and Non-trusted constraints and performance.

Unless you did some solid measurements that demonstrated that the constraint verification of the DELETE operation are a performance bottleneck, let the engine do its work.

Remus Rusanu
+2  A: 

How can your DELETE time out? Don't you have indexes on your foreign keys?

erikkallen
A: 

Do not under any circumstances disable the constraints. This is an extremely stupid practice. You cannot maintain data integrity if you do things like this. Data integrity is the first consideration of a database because without it, you have nothing.

The correct method is to delete from the child tables before trying to delete the parent record. You are probably timing out because you have set up cascading deltes which is another bad practice in a large database.

HLGEM