The CONSTRAINT Keyword

tags: #sql/constraints

Naming Constraints

You can name a constraint using the CONSTRAINT keyword followed by a constraint name after the attribute's data type (refer to constraints).

CREATE TABLE table_name (
   column1 data_type CONSTRAINT constraint_name constraint_type,
   column2 data_type CONSTRAINT constraint_name constraint_type,
   ... // alternative 
   CONSTRAINT constraint_name constraint_type (column1, column2, ...),
   ...
);

Example:

CREATE TABLE EMPLOYEE (
	...
	Dno INT NOT NULL,
	...
	CONSTRAINT EMP_DEP_FK 
		FOREIGN KEY (Dno) REFERENCES DEPARTMENT (Dnumber)
		ON DELETE CASCADE 
		ON UPDATE CASCADE
)
What is the purpose of giving names to constraints?

Altering Constraints

Adding new constraints

ALTER TABLE table_name  
ADD CONSTRAINT <constraint_name> <constraint_type> (column(s)...);

Example:

ALTER TABLE Persons  
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

Dropping constraints

ALTER TABLE table_name  
DROP CONSTRAINT <constraint_name>;
Powered by Forestry.md