Skip to content

Commit c251ecf

Browse files
committed
understanding primary key integrity constraint
1 parent 2d2023d commit c251ecf

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
use temp_db;
2+
3+
show tables;
4+
5+
-- here primary key simplye means = NOT NULL + UNIQUE
6+
-- it is used to uniquely identify a tuple/record
7+
8+
create table temp1(id int PRIMARY KEY, fullname varchar(15));
9+
10+
insert into temp1 values(1, 'SANOJ'); -- no error
11+
insert into temp1 values(2, 'Kumar'); -- no error
12+
13+
insert into temp1 values(1, 'DEEPAK'); -- gives error
14+
15+
insert into temp1 values(NULL, 'DEEPAK kumar'); -- gives error
16+
17+
18+
-- tables can also be defined like this
19+
create table temp2(id int, fullname varchar(15), primary key(id)); -- here id is primary key
20+
21+
create table temp3(id int, fullname varchar(15), primary key(id, fullname)); -- here id and fullname is primary key
22+
23+
insert into temp3 values(1, 'SANOJ'); -- no error
24+
insert into temp3 values(1, 'DEEPAK'); -- no error because combination is primary key
25+
insert into temp3 values(NULL, 'DEEPAK') -- gives error because column can not contain null values
26+

unique_integrity_constrain.sql

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ show tables;
77
create table stu_2(stu_id int UNIQUE, stu_name varchar(15));
88

99
create table stu_3(stu_id int, stu_name varchar(15), unique(stu_id)); -- here we have provided the constraint at column level
10+
-- here it means stu_id combinaton must be unique what if i have written
11+
create table stu_4(stu_id int, stu_name varchar(15), unique(stu_id, stu_name));
12+
-- it means combination of id and name must be unique
13+
-- like 1, sanoj is different than 1, deepak
1014

1115
-- here stu_id must be unique
1216

0 commit comments

Comments
 (0)