3 Integrity constraints and groupby having clause
3 Integrity constraints and groupby having clause
Constraints
Integrity Constraints in SQL
1) NOT NULL CONSTRAINT
to disallow the null values
2) Table Constraints
Primary key
Check
Not null
Foreign key
Example
Create table Sailors (sid number,
sname char(10) not null,
rating number, age number(5,2),
primary key (sid),
check (rating >=1 and rating <=10)
Create table Reserves (sid number, bid number,
day date,
foreign key (sid) references sailors (sid),
foreign key (bid) references boats (bid),
constraint noInterLake
check (‘InterLake’ <>(select B.bname from
boats B where B.bid = Reserves.bid))
3) Domain Constraints and distinct
types
Studid and sid must be domain compatible (should have same datatype)
Similarly data type of cid of course reln should be same as datatype of courseid
of enrolled reln
Referrential Integrity Constraint
Students (referrenced reln) Course reln
Sid Name Age cid Grade Studid cid Course
1 A 18 name
C2 AA 5
2 B 19 C1 VB
C3 B+ 6
3 C 20 C2 VC++
C1 A+ 4
4 D 21 C3 JAVA
C4 A- 2
5 E 22 C4 ASP
Enrolled (referrencing reln)
6 F 23
Insert (c1, A+, 7 ) in Enrolled reln is invalid becoz studid <> sid
Foreign key constraint will check for this violation
Delete (6, F, 23 ) from student reln should also delete (c3, B+, 6) from
enrolled reln
Referrential Integrity Constraint
Students (referrenced reln) Course reln
Sid Name Age cid Grade Studid cid Course
1 A 18 name
C2 AA 5
2 B 19 C1 VB
C3 B+ 6
3 C 20 C2 VC++
C1 A+ 4
4 D 21 C3 JAVA
C4 A- 2
5 E 22 C4 ASP
Enrolled (referrencing reln)
6 F 23
Every studid value in enrolled must appear in student reln since enrolled
references student .
Create table Enrolled ( studid char(10),
cid char (10),
grade char (10),
foreign key (studid) references students(sid)
foreign key (cid) references course (cid)
on delete cascade,
on update no action);
Create table student (sid char(20), name char (20), age number,
honors char(10) not null, primary key (sid), foreign key (honors)
references course (cid));