SQL Constraints
SQL Constraints
Primary Key Constraint
Step 1:
(first ensure the field is NOT NULL)
Syntax to assign to the column the not null constraint:
alter table tablename alter column column int not null
Step 2:
Syntax:
ALTER TABLE tablename ADD CONSTRAINT constraintname PRIMARY KEY (fieldname);
Example:
Alter table Employees add constraint PK_EmpID PRIMARY KEY (EmployeeID)
Foreign key constraint
Example:
alter table Orders | -- table name |
add constraint FK_EID | – constraint name |
foreign key (ShipperID) | -- column that will become a foreign key |
references Shippers (ShipperID) | -– table and column name to which it links |
Default constraint
Syntax:
Alter table tablename add constraint constraintname default value for column
Example:
Alter table Orders add constraint df_Constraintname default getdate() for orderdate
Check Constraint
Syntax:
Alter table Products add constraint ch_price check (price >= 0)
Example:
Alter table Products add constraint ch_price check (price >= 0)
alter table products drop constraint ch_price

Comments
Post a Comment