Monday 13 August 2012

MySQL Constraints and Foreign Keys

This is primarily for my reference alone. I continually find myself using these three SQL commands when working with constraints and foreign keys.

-- Add a foreign key constraint. I can also SET NULL, NO ACTION or RESTRICT instead of cascade
ALTER TABLE sop_version_ancestry ADD CONSTRAINT fk_sop_version_ancestry_sop
FOREIGN KEY (sop_id) REFERENCES sop(sop_id)
ON DELETE CASCADE ON UPDATE CASCADE

-- Show what constraints exist in the table (because phpmyadmin doesn't show ought)
SHOW CREATE TABLE sop_version_ancestry

-- Delete a constraint once I know what it's called from the command above
ALTER TABLE sop_version_ancestry DROP FOREIGN KEY fk_sop_version_ancestry_sop

No comments:

Post a Comment