Skip to main content

Delete or Update Rows Referenced by MySQL Foreign Keys

· One min read
Apache Wangye
Software developer and technical writer

MySQL rejects a parent-row delete or key update when dependent child rows would violate a foreign-key constraint.

The safest solution is to handle dependencies explicitly:

START TRANSACTION;
DELETE FROM order_items WHERE order_id = 1001;
DELETE FROM orders WHERE id = 1001;
COMMIT;

When the domain requires automatic cleanup, define the relationship with an appropriate action:

FOREIGN KEY (order_id)
REFERENCES orders(id)
ON DELETE CASCADE
ON UPDATE CASCADE

Use CASCADE only when deleting the parent should unquestionably delete children. SET NULL may be more appropriate when history must remain.

Temporarily disabling checks is risky:

SET FOREIGN_KEY_CHECKS = 0;
-- controlled maintenance operation
SET FOREIGN_KEY_CHECKS = 1;

Re-enabling the variable does not automatically validate inconsistent rows created while checks were disabled. Use it only for reviewed imports or maintenance, in a dedicated session, with backups and post-operation integrity checks.

Page views: --

Total views -- · Visitors --