ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint_definition; |
ALTER TABLE employee ADD CONSTRAINT EmpPrimKey PRIMARY KEY(ssn); |
|
ALTER TABLE table_name DROP CONSTRAINT constraint_name ;
|
ALTER TABLE employee DROP CONSTRAINT EmpPrimKey;
|
|
ALTER TABLE table_name DROP FOREIGN KEY constraint_name ;
|
 
 
|
Consider the cycle created by the following referential integrity constraints:
employee(dno) → department(dnumber) department(mgrssn) → employee(ssn) |
|
CREATE TABLE emp1 ( ssn CHAR(9), dno INTEGER, CONSTRAINT empPrimaryKey PRIMARY KEY (ssn), CONSTRAINT empForeignKey1 FOREIGN KEY (dno) REFERENCES dept1(dnumber) ); CREATE TABLE dept1 ( dnumber INTEGER, mgrssn CHAR(9), CONSTRAINT deptPrimaryKey PRIMARY KEY (dnumber), CONSTRAINT deptForeignKey1 FOREIGN KEY (mgrssn) REFERENCES emp1(ssn) ); |
Result:
SQL> CREATE TABLE emp1 ( ssn CHAR(9), dno INTEGER, CONSTRAINT empPrimaryKey PRIMARY KEY (ssn), CONSTRAINT empForeignKey1 FOREIGN KEY (dno) REFERENCES dept1(dnumber) ) ERROR 1005 (HY000): Can't create table 'companyDB.emp1' (errno: 150) (My comment: this error message SUCKS. No reason given ??? I guess you get what yoy pay for. Oracle's error message is much clearer...) |
|
|
Example:
CREATE TABLE emp1 ( ssn CHAR(9), dno INTEGER, CONSTRAINT empPrimaryKey PRIMARY KEY (ssn) ); CREATE TABLE dept1 ( dnumber INTEGER, mgrssn CHAR(9), CONSTRAINT deptPrimaryKey PRIMARY KEY (dnumber) ); |
|
INSERT INTO emp1 VALUES ('444444444', 12); INSERT INTO dept1 VALUES (12, '444444444'); |
Result:
SQL> INSERT INTO emp1 VALUES ('444444444', 12); ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`companyDB`.`emp1`, CONSTRAINT `empForeignKey1` FOREIGN KEY (`dno`) REFERENCES `dept1` (`dnumber`)) |
Reason:
|
|
Deferred constraint:
|
ALTER TABLE emp1 DROP CONSTRAINT empForeignKey1; ALTER TABLE emp1 ADD CONSTRAINT empForeignKey1 FOREIGN KEY (dno) REFERENCES dept1(dnumber) INITIALLY DEFERRED DEFERRABLE ; |
MySQL implementation issue:
|
|
|
drop table dept1; drop table emp1; |
(in that order !) -- because there is a foreign key constraint in dept1...