Thursday, 20 August 2020

Enforcing primary key and Foreign key constraints.

Primary Key:- A Primary key basically is used to identifies uniquely each record in the table. primary key must include unique value, and can not contain null values. primary key A table can have only 1 primary key.
Example:-
Create Primary Key:-
create table tblpersons
(
Id int not null Primary key,        ---> Id  column is a primary key
name varchar(50) Not null,
email varchar(50) not null,
genderid int 
)
select * from tblpersone;


create table tblgender
(

id int not null primary key,
gender varchar(10) not null

)

select * from tblgender


Foreign Key:-Foreign key is a key used to a link to two table together. Foreign key is a key in one table that refer to the primary key in another table.

Example:- 
How to add foreign key in a exiting table.

Alter table tblpersons add constraint tblpersone_genderid_FK foreign key(genderid) references primary key (id).

Notes:- Foreign key combination of column whose value doesn't miss match a primary key in a different table.

A foreign key in one table indicate a primary key in another table. The foreign key constraint  prevents invalid data form being inserted into foreign key column.The data you are inserting into foreign key  column, should be same data as the primary key column of the another table.

Adding a default constraint:-

A default column can be specified using defaults constraint. The default constraint is used to insert a default value into the column.The default value will be added to all new records, if no other value is specified, including null. 

Example:-

alter table tblpersons add constraint DF_tblpersone_genderid default 3 for genderid

How to drop Default constraint

alter table tbpersons drop constraint DF_tblpersone_genderid

DF_tblpersone_genderid- this is default constraint name

after add default constraint then insert data in table

insert into tblpersone(id,name,email) values(06,'Kaif','kaif@gmail.com')    

genderid column value by default insert 3.



3 comments: