Articles → SQL SERVER → Constraints In SQL Server
Constraints In SQL Server
What Is A Constraint?
Primary Key Constraint
- Contains unique value
- It should not be null
Example
Create table Test (
PK_ID int,
sName varchar(100),
Primary key (PK_ID)
)
insert into Test values(1,'hi')
insert into Test values(1,'hi')
Apply Primary Key Constraint To The Existing Table
ALTER TABLE Test Add Primary key (PK_ID)
Create table Test (
PK_ID int not null,
sName varchar(100)
)
Foreign Key Constraint
-- Person
Create table Person (
PersonID int,
FullName varchar(100),
CityID int,
Primary key (PersonID),
Foreign key (CityID) References City (CityID)
)
-- City
Create table City (
CityID int,
City varchar(50),
primary key (CityID)
)
Foreign key (CityID) References City (CityID)
insert into City values(1,'Gurgaon')
insert into Person values('karan Gupta',1)
PersonID | FullName | CityID |
---|
1 | Karan Gupta | 1 |
insert into Person values('karan',2)