SQL Server


// ------------------------
// foreign key constraint
// ------------------------
// InstructorId is the primary key in the Instructor table and is a foreign key in the Course table
// to enforce data integrity, need to set InstructorId as a foreign key in the FK table (Course)
// the following rules can be enforced for a foreign key constraint
//  - PK table row cannot be deleted if it's being used by the FK table
//  - FK table column can only be populated with values that exist in the PK table
// can also add the constraint via the create table command (see unique key example below)
alter table Course 
  add constraint FK_Course_Instructor_InstructorId foreign key (InstructorId) 
  references Instructor(InstructorId)

// ------------------------
// default constraint
// ------------------------
// used to set a default value for a column
// in this example, if a row is inserted w/o a value of BuildingId, it will be defaulted to 3
alter table Course add constraint DF_Course_BuildingId default (3) for BuildingId

// ------------------------
// check constraint
// ------------------------
// used to limit the range of values allowed for a column
alter table Course add constraint CK_Course_BuildingId check (BuildingId > 0 and BuildingId < 1000)

// ------------------------
// unique key constraint
// ------------------------
// table can only have one primary key but can have multiple unique keys
// may want to enforce uniqueness on other columns
alter table Student add constraint UQ_Student_Email unique (Email)

// ----------------------------------------------------
// unique key constraint (composite) via create table
// ----------------------------------------------------
create table Source
(
  SourceId int,
  TypeId int,
  Name varchar(20),
  Constraint UQ_Source_SourceId_TypeId unique (SourceId, TypeId)
)

// ------------------------
// delete a constraint
// ------------------------
alter table Student drop constraint UQ_Student_Email