0% found this document useful (0 votes)
45 views77 pages

Dbms Revaan Final

Uploaded by

24priyanka02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views77 pages

Dbms Revaan Final

Uploaded by

24priyanka02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

Exercise No:1

Date: 20/08/24 STUDY ON BASIC SQL COMMANDS- ORACLE

1) Data Definition Language:

(i) Create:

Syntax: create table <table_name> (<colname_1> dt1 (constraint), <colname_2> dt2 (constraint)
….., <colname_n> dtn (constraint));

Example: create table student(id number(10), name varchar2(12), address varchar2(20));

(ii) Description of Table:

Syntax: desc <table_name>;

Example: desc student;

(iii) Alter:

Syntax: alter table <table_name> add <col_name> datatype;

Example: alter table student add bloodgroup char(2);

(iv) Modify:

Syntax: alter table <table_name> modify <col_name> datatype;

Example: alter table student modify bloodgroup char(3);

(v) Delete:

Syntax: alter table <table_name> drop column <col_name>;

Example: alter table student drop column bloodgroup;

(vi) Drop:

Syntax: drop table <table_name>;

Example: drop table student;

2) Data Manipulation Language:

Page | 1
(i) Insert:

Syntax: insert into< table_name> values(value_1,value_2,…,value_n);

Example: insert into student values(1,’Itachi’,1234);

(ii) Update:

Syntax: update <table_name> set <col_name>=<new_value> where <condition>;

Example: update student set phno=9876543210 where id=1;

(iii) Delete:

Syntax: delete from <table_name> where <condition>;

Example: delete from student where id=1;

(iv) Select:

Syntax: select <attribute_name> from <table_name>;

Example: select name from student;

3) Data Control Language:

(i) Grant:

Syntax: grant <list_of_privileges> on <table_name> to user;

Example: grant select on student to public;

(ii) Revoke:

Syntax: revoke <list_of_privileges> on <table_name> from user;

Example: revoke select on student from public;

(iii) Role:

Syntax: create role <role_name>;

Example: create role manager;

4) Transaction Control Language:

(i) Commit:

Syntax: commit;

2
Example: insert into student values(1,’Itachi’,1234);
commit;

(ii) Roll Back:

Syntax: rollback;

Example: insert into student values(1,’Itachi’,1234);


commit;
delete from student;
rollback;

(iii) Save Point:

Syntax: savepoint a;

Example: insert into student values(1,’Itachi’,1234);


savepoint a;
insert into student values(2,’Uchita’,1244);
savepoint b;
rollback to a;
commit;

EXERCISE NO:2
BASIC DDL AND DML COMMANDS
DATE:27/08/2024

UNIVERSITY MANAGEMENT SYSTEM


schemas

Students: StudentID , FirstName, LastName, Email, PhoneNumber, DateOfBirth, DepartmentID

Courses: CourseID , CourseName, Credits, DepartmentID , InstructorID

Instructors: InstructorID , FirstName, LastName, Email, PhoneNumber, DepartmentID

Enrollments: EnrollmentID, StudentID, CourseID , EnrollmentDate, Status

Departments: DepartmentID , DepartmentName, DepartmentHead


3
Grades: Grade , EnrollmentID, Gradepoint

______________________________________________________________________________________

AIM: TO WORK WITH THE BASIC DDL AND DML COMMAND BY CREATING AN UNIVERSITY

MANAGEMENT SYSTEM

1.Use all DDL statements and define the table structure.

create table students (studentid varchar(20), firstname varchar(20), lastname varchar(20), email varchar(20),

phonenumber varchar(20), dob date, deptid varchar(20));

create table courses (courseid varchar(20), coursename varchar(20), credits varchar(20), deptid varchar(20),

instructorid varchar(20));

create table instructors (insid varchar(20), firstname varchar(20), lastname varchar(20),

email varchar(20), phonenumber varchar(20), deptid varchar(20));

create table enrollments (enid varchar(20), studentid varchar(20), courseid varchar(20), endate date,

status varchar(20));

create table departments (deptid varchar(20), deptname varchar(20), departmenthead varchar(20));

create table grades (grade varchar(20), enid varchar(20), gradepoint varchar(20));

2.insert atleast 10 records to each table.

4
STUDENT TABLE :
1) insert into students values ('S001', 'john','doe', '[email protected]', '1234567890', '2000-01-15', 'D01');

insert into students values ('S002', 'jane','Smith', '[email protected]', '2345678901', '2001-02-10', 'D02');

insert into students values ('S003', 'michael','Brown', '[email protected]', '1234567892', '2000-03-05',


'D01');

insert into students values ('S004', 'David','clark', '[email protected]', '4567890123', '2001-04-20',


'D03');

insert into students values ('S005', 'olivia','johnson', '[email protected]', '5678901234', '2000-05-25',


'D02');

insert into students values ('S006', 'emily','davis', '[email protected]', '6789012345', '2001-06-30', 'D01');

insert into students values ('S007', 'james','Wilson', '[email protected]', '7890123456', '2000-07-10',


'D03');

insert into students values ('S008', 'sophia','miller', '[email protected]','8901234567', '2001-08-15',


'D02');

insert into students values ('S009', 'ethan','more', '[email protected]', '9012345678', '2000-09-20', 'D01');

insert into students values ('S010', 'mia','Anderson', '[email protected]', '0123456789', '2001-10-01',


'D03');

5
COURSES TABLE :
2) insert into courses values ('C001', 'Math101', '3', 'D01', 'I001');

insert into courses values ('C002', 'Physics101', '4', 'D01', 'I002');

insert into courses values ('C003', 'Chem101', '3', 'D02', 'I003');

insert into courses values ('C004', 'Bio101', '3', 'D02', 'I004');

insert into courses values ('C005', 'Cs101', '4', 'D01', 'I005');

insert into courses values ('C006', 'hist101', '3', 'D03', 'I006');

insert into courses values ('C007', 'eng101', '3', 'D03', 'I007');

insert into courses values ('C008', 'Econ101', '2', 'D03', 'I008');

insert into courses values ('C009', 'Psych101', '3', 'D02', 'I009');

insert into courses values ('C010', 'art101', '3', 'D01', 'I010');

6
INSTRUCTOR TABLE :
3) insert into instructors values ('I001', 'alice', 'anderson', '[email protected]', '1234567891', 'D01');

insert into instructors values ('I002', 'Johnson', 'Doe', '[email protected]', '2345678912', 'D02');

insert into instructors values ('I003', 'charlie', 'williams', '[email protected]', '3456789123', 'D03');

insert into instructors values ('I004', 'diana', 'martinez', '[email protected]', '4567891234', 'D01');

insert into instructors values ('I005', 'evan', 'garcia', '[email protected]', '5678912345', 'D02');

insert into instructors values ('I006', 'florida', 'robinson', '[email protected]', '6789123456', 'D03');

insert into instructors values ('I007', 'george', 'levis', '[email protected]', '7891234567', 'D01');

insert into instructors values ('I008', 'hannar', 'walker', '[email protected]', '8912345678', 'D02');

insert into instructors values ('I009', 'isaac', 'hall', '[email protected]', '9123456789', 'D03');

insert into instructors values ('I010', 'julia', 'young', '[email protected]', '1912345678', 'D01');

ENROLLMENT TABLE :
4) insert into enrollments values ('E001', 'S001', 'C001', '2023-01-15', 'Active');

7
insert into enrollments values ('E002', 'S002', 'C002', '2023-02-10', 'Active');

insert into enrollments values ('E003', 'S003', 'C003', '2023-03-05', 'completed');

insert into enrollments values ('E004', 'S004', 'C004', '2023-04-20', 'Active');

insert into enrollments values ('E005', 'S005', 'C005', '2023-05-25', 'Completed');

insert into enrollments values ('E006', 'S006', 'C006', '2023-06-30', 'Active');

insert into enrollments values ('E007', 'S007', 'C007', '2023-07-10', 'Active');

insert into enrollments values ('E008', 'S008', 'C008', '2023-08-15', 'active');

insert into enrollments values ('E009', 'S009', 'C009', '2023-09-20', 'completed');

insert into enrollments values ('E010', 'S010', 'C010', '2023-10-05', 'active');

DEPARTMENT TABLE :
5) insert into departments values ('D01', 'literature', 'laura brown');

insert into departments values ('D02', 'mathematics', 'tom barris');


8
insert into departments values ('D03', 'physics', 'nancy clark');

insert into departments values ('D04', 'biochemistry', 'james wilson');

insert into departments values ('D05', 'engineering', 'olivia green');

insert into departments values ('D06', 'philosophy', 'david thomson');

insert into departments values ('D07', 'geology', 'sophia adams');

insert into departments values ('D08', 'political science', 'michael scott');

insert into departments values ('D09', 'art history', 'emma robinson');

insert into departments values ('D10', 'sociology', 'liam levis');

GRADE TABLE :
5) insert into grades values ('A', 'E001', '4.0');

insert into grades values ('B+', 'E002', '3.5');

insert into grades values ('B', 'E003', '3.0');

9
insert into grades values ('C+', 'E004', '2.5');

insert into grades values ('C', 'E005', '2.0');

insert into grades values ('D+', 'E006', '1.5');

insert into grades values ('D', 'E007', '1.0');

insert into grades values ('F', 'E008', '0.0');

insert into grades values ('A-', 'E009', '3.7');

insert into grades values ('B-', 'E010', '2.1');

ALTER TABLE ( ASSIGNNING PRIMARY AND FOREIGN KEY) :


alter table students
add primary key (studentid);

alter table students


add foreign key (deptid) references departments(deptid);

10
alter table courses
add primary key (courseid);

alter table courses


add foreign key (deptid) references departments(deptid),
add foreign key (insid) references instructors(insid);

alter table instructors


add primary key (insid);

alter table instructors


add foreign key (deptid) references departments(deptid);

alter table enrollments


add primary key (enid);

alter table enrollments


add foreign key (studentid) references students(studentid),
add foreign key (courseid) references courses(courseid);

alter table departments


add primary key (deptid);

11
alter table departments
add foreign key (deptid) references instructors(deptid);

alter table grades


add primary key ( grade);

alter table grades


add foreign key (enid) references enrollments(enid);

12
UPDATION OF RECORDS :
3. Update the Credits of the course with specific CourseID in the Courses table from 3 to 4.
update courses set credits = 4
where courseid=’C001’;

4. Update the Status in the Enrollments table for certain EnrollmentID to "Completed".
Update enrollments
Set status =’completed’
Where enid=’E001’;

5. Delete the record of a department from the Departments table based on some condition.
Delete from departments where departmentid=’D01’;

6. Draw the ER Diagram for library management system database schema described above.

RESULT: The DDL and DML commands for the university management system is created and
successfully executed.
13
EXERCISE NO:3
BASIC SQL AND VIEWS
DATE:03/09/2024

AIM : TO VIEW ALL THE RECORDS IN THE UNIVERSITY MANAGEMENT SYSTEM

1. Create a view to display StudentID, FirstName, LastName, and Email from the Students table.

Create view display as select studentid,firstname,lastname,email from student

Select * from display

2.Find all courses that have credits between 3 and 5.

Select * from courses


Where credits between 3 AND 5;

3.Retrieve all enrollments made between January 1, 2024, and June 30, 2024.

Select * from enrollments where endate between ’01-JAN-2024’ and ’30-JUN-2024’;

14
4.Retrieve all instructors who belong to department IDs 4 or 5.

Select * from instructor where deptid in (‘D05’,’D04’);

5. Find all courses that are not in department IDs 1, 2, or 3.

Select * from courses where deptid not in (‘D01’,’D02’,’D03’);

6.Retrieve all instructors not working in department IDs 6 or 7.

Select * from instructor Where deptid Not in (6, 7);

15
7. Find all students with last names starting with 'S'.
Select * from student where lastname like ‘s%’;

8.Retrieve all instructors who have a PhoneNumber ending with '5'.

Select * from instructor where phoneno like ‘%5’;

9. Find all students who are either in department 1 or have an email ending in '@gmail.com'.
Select * from student where deptid =’ D01’ OR email like ‘ % @ gmail.com’;

16
10.List all courses with credits greater than 3 and CourseName containing 'Science'.
Select * from courses where credits >3 and coursename like ‘ %science’;

11. List all students ordered by LastName and then by FirstName.

Select * from student order by lastname, firstname ;

12. Show all instructors ordered by DepartmentID and then by LastName

Select * from instructor order by deptid,lastname;

17
ORDER BY DEPARTMENT ID :

ORDER BY LASTNAME :

13. List all courses that do not have an assigned InstructorID (InstructorID is NULL).
select * from courses where instructorid is null;

18
15. Compute the number of days remaining until the course ends, assuming EndDate is known
(replace EndDate with the actual column if available).

Select coursed coursename trun(enddate) as endate_truncated,trunc(enddate)_trunc(sysdate)


As days_ remainning from courses;

RESULT: The basic sql and views for university management system is created and executed
successful.

19
EXERCISE NO:4
AGGREGATE FUNCTIONS & STRING FUNCTIONS
DATE:10/09/2024

AIM : TO WORK WITH THE SQL AGGREGATE FUNCTIONS AND STRING FUNCTIONS TO
ANALYSIS AND MANIPULATION.

______________________________________________________________________________________

1. Find the number of students in each department.

Select deptname,(select count(*) from student where deptid = d.deptid) as NUM_STUDENTS from
department d;

2. Find the total number of courses each instructor teaches.

select insid, (select count(*) from courses where insid = i.insid) as total_courses from instructor i;

20
3. Calculate the average grade point for each department.

select deptname, (select avg(gradepoint) from grades where enid in (select enid from enrollments wherer
studentid in (select studentid from student where deptid = d.deptid))) as average_gradepoint from
department d;

4. Find the number of students who have grades above 8 in their courses.

select count(distinct e.studentid) as num_students from enrollments e where e.enid in (select g.enid from
grades g where g.gradepoint > 8);

21
5. List the number of students who are enrolled in more than 2 courses.

select studentid, count(enid) as course_count from enrollments group by studentid having count(enid) > 2;

6. Count the number of courses offered in each department.

select depid, count(courseid) as course_count from courses group by depid;

7. Show the names of instructors in uppercase.

select upper(firstname) as firstname, upper(lastname) as lastname from instructor;

8. Retrieve the first 3 characters of each department name.


22
select substr(deptname, 1, 3) as dept_name_prefix from department;

9. Show the length of each student's email address.

select studentid, length(email) as email_length from student;

10. Display the concatenated first and last names of students.

select studentid, firstname || ' ' || lastname as full_name from student;

23
RESULT: The aggregate and string function for university management system is created and
successfully executed.
24
EXERCISE NO:5
JOINS
DATE:21/09/2024

AIM : TO WORK WITH THE SQL JOINS TO RETRIEVE AND ANALYZE RELATED DATA FROM
MULTIPLE TABLES.

______________________________________________________________________________________

1.Extract the day and month from the student's date of birth.

select extract(day from s.dob) as birth_day, extract(month from s.dob) as birth_month from student s join
department d on s.deptid = d.deptid;

2. List all students along with their enrolled courses.

select s.studentid, s.firstname, c.coursename from student s join enrollments e on s.studentid = e.studentid
join courses c on e.courseid = c.courseid;

25
3. Show all students and the departments they belong to.

select s.studentid, s.firstname, d.deptname from student s join department d on s.deptid = d.deptid order
by s.studentid;

4. Show all students along with their grade and course.

select s.studentid, s.firstname, c.coursename, g.grade from student s join enrollments e on s.studentid =
e.studentid join courses c on e.courseid = c.courseid join grades g on e.enid = g.enid order by s.studentid;

26
5. List all instructors and the departments they belong to using a natural join.

select i.insid, i.firstname, d.deptname from instructor i natural join department d;

6 . List all possible combinations of departments and students.

select d.deptid, d.deptname, s.studentid, s.firstname from department d cross join student s;

27
28
29
7. Find all enrollments where the grade point is greater than 7.5.

select e.enid, g.gradepoint from enrollments e join grades g on e.enid = g.enid where g.gradepoint > 7.5;

8. List all students and their enrollments, including students who are not enrolled in any course.

select s.studentid, s.firstname, e.enid, e.courseid from student s left join enrollments e on s.studentid =
e.studentid;

30
9. Display all instructors and the courses they teach, including instructors who are not teaching any course.

select i.insid, c.coursename from instructor i left join courses c on i.insid = c.insid order by i.insid,
c.coursename;

10. List pairs of students from the same department.

select s1.studentid as student1id, s1.firstname as student1firstname, s2.studentid as student2id,


s2.firstname as student2firstname, s1.deptid from student s1 join student s2 on s1.deptid = s2.deptid and
s1.studentid < s2.studentid order by s1.deptid, s1.studentid, s2.studentid;

RESULT: The join function for the university management system is created and successfully
executed.
31
EXERCISE NO : 6
SUBQUERY
DATE :

AIM : To work with the subqueries for university management system.

1. Find students who are enrolled in courses that have more credits than the average
credits across all courses.
Select s.StudentID, s.FirstName from Student s join Enrollments e ON s.StudentID =
e.StudentID join Courses c on e.CourseID = c.CourseID where c.Credits > ( select
avg(Credits) from Courses.

2. List courses that have more enrolled students than the average number of students
enrolled in all courses.
select c.CourseID, c.CourseName from Courses c join ( select CourseID, count(StudentID)
as EnrolledCount from Enrollments group by CourseID) e on c.CourseID = e.CourseID
e.EnrolledCount > (select avg(EnrolledCount) from ( select count(StudentID) as
EnrolledCount from Enrollments group by CourseID ) avgCounts);

32
3. Find the number of courses taught by each instructor along with the average grade
of students in those courses.
Select i.InstructorID, i.FirstName, i.LastName, count(c.CourseID) as
NumberOfCourses, avg (g.Gradepoint) as AverageGrade from Instructors i left join Courses
c ON i.InstructorID = c.InstructorID left join Enrollments e on c.CourseID = e.CourseID
left Join Grades g ON e.EnrollmentID = g.EnrollmentID Group By i.InstructorID,
i.FirstName, i.LastName;

4. List courses that have more students enrolled than the average number of students
across all courses.
select c.CourseID, c.CourseName from Courses c join Enrollments e on c.CourseID =
e.CourseID Group By c.CourseID, c.CourseName having count(e.StudentID) > (select
avg(NumberOfStudents) from (select count(StudentID) as NumberOfStudents from
Enrollments Group By CourseID) as AvgStudents);

5. List all instructors who have students enrolled in their courses


33
select distinct i.InsID, i.FirstName, i.LastName, i.Email, i.PhoneNumber, i.DeptID From
Instructor i JOIN Courses c ON i.InsID = c.InsID join Enrollments e on c.CourseID =
e.CourseID;

6. Find the total number of enrollments in each course.


select c.CourseID, c.CourseName, count(e.EnrollmentID) as TotalEnrollments from
Courses c left Join Enrollments e on c.CourseID = e.CourseID Group by c.CourseID,
c.CourseName;

7. List students along with their total enrollments.

34
select s.StudentID, s.FirstName, s.LastName, count(e.EnrollmentID) as TotalEnrollments
from Student s left join Enrollments e on s.StudentID = e.StudentID group by s.StudentID,
s.FirstName, s.LastName;

8. Display students with a label based on their grade: 'Excellent' if the grade is above
90, 'Good' if the grade is between 70 and 90, and 'Needs Improvement' otherwise.
select s.StudentID, s.FirstName, s.LastName, case when avg(g.Gradepoint) > 90 then
'Excellent' when avg(g.Gradepoint) between 70 and 90 then 'Good' else 'Needs
Improvement' end as GradeLabel from Student s left Join Enrollments e on s.StudentID =
e.StudentID left Join Grades g ON e.EnID = g.EnID group By s.StudentID, s.FirstName,
s.LastName;

35
9. List all students whose grades are higher than any student enrolled in specific
course.
select distinct s.StudentID, s.FirstName, s.LastName from Students s where s.StudentID in
(select e.StudentID from Enrollments e where e.CourseID = 'SPECIFIC_COURSE_ID' and
(select avg(g2.Gradepoint) from Grades g2 where g2.EnID = e.EnID) < (select
avg(g3.Gradepoint) from Grades g3 where g3.EnID in (SELECT e2.Enid from Enrollments
e2 where e2.StudentID = s.StudentID)));

10. Find courses with a lower number of credits than all courses in the 'Computer
Science' department.
select c.CourseID, c.CourseName from Courses c where c.Credits < all (select c2.Credits
from Courses c2 where c2.DeptID = (select DeptID from Department where DeptName =
'Computer Science'));

RESULT :The subqueries for the university management is created and successfully
executed.

36
EXERCISE NO : 7
DATE : PL/SQL - BASICS

AIM : To work with the basic PL/SQL commands in oracle.

1.Create a PL/SQL block that calculates the sum of the first N natural numbers.

DECLARE
N NUMBER:=0;
N1 NUMBER:=&N1;
I NUMBER;
BEGIN
FOR I IN 1..N1
LOOP
N:=N+I;
END LOOP;
DBMS_OUTPUT.PUT_LINE('SUM OF FIRST '||N1||' NATURAL NUMBERS IS '||N);
END;

/
2. Write a PL/SQL function to reverse a given string.

DECLARE
-- declare variable str , len
-- and str1
str VARCHAR(20) := '&STR';
37
len NUMBER;
str1 VARCHAR(20);
BEGIN
-- Here we find the length of string
len := Length(str);

-- here we starting a loop from max len to 1


FOR i IN REVERSE 1.. len LOOP
-- assigning the reverse string in str1
str1 := str1 || Substr(str, i, 1);
END LOOP;

dbms_output.Put_line('Reverse of string is '|| str1);


END;
/

3. Create a PL/SQL procedure to check whether a number is palindrome or not.


DECLARE
N NUMBER:=&N;
NN NUMBER;
REV NUMBER:=0;
R NUMBER;
BEGIN

38
NN:=N;
WHILE N>0
LOOP
R:=MOD(N,10);
REV:=REV*10+R;
N:=TRUNC(N/10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('REVERSED NUMBER IS '||REV);
IF REV=NN THEN
DBMS_OUTPUT.PUT_LINE('GIVEN NUMBER IS A PALINDROME ');
else
DBMS_OUTPUT.PUT_LINE('GIVEN NUMBER IS NOT A PALINDROME ');
END IF;
END;
/

4.Write a PL/SQL block to display Fibonacci series up to a given number.


DECLARE
LIMIT NUMBER:=&LIMIT;
FIR NUMBER:=0;
SEC NUMBER:=1;
SUM1 NUMBER:=0;
BEGIN

39
DBMS_OUTPUT.PUT_LINE('FIBONACCI SERIES :');
WHILE SUM1 <=LIMIT LOOP
DBMS_OUTPUT.PUT_LINE(SUM1);
FIR:=SEC;
SEC:=SUM1;
SUM1:=FIR+SEC;
END LOOP;
END;
/

5.Write a PL/SQL block that raises an exception if the input number is negative when
calculating its square root.

DECLARE
N NUMBER:=&N;
EX_INVALID EXCEPTION;
BEGIN
IF N<0 THEN
RAISE EX_INVALID;
ELSE

40
DBMS_OUTPUT.PUT_LINE('SQUARE ROOT :'||SQRT(N));
END IF;
EXCEPTION
WHEN
EX_INVALID then
DBMS_OUTPUT.PUT_LINE('N MUST BE GREATER THAN ZERO');
END;
/

6.Create a PL/SQL procedure to calculate the power of a number.

DECLARE
B NUMBER:=&B;
E NUMBER:=&E;
C NUMBER;
PROCEDURE FINDPOW(X IN NUMBER,Y IN NUMBER,Z OUT NUMBER) IS
BEGIN
Z:=POWER(X,Y);
END;
BEGIN
FINDPOW(B,E,C);
DBMS_OUTPUT.PUT_LINE('POWER :'||C);
END;
41
/

7.Write a PL/SQL function to calculate the GCD (Greatest Common Divisor) of two
numbers.

DECLARE
N1 NUMBER:=&N1;
N2 NUMBER:=&N2;
NR NUMBER;
DR NUMBER;
R NUMBER;
FUNCTION FINDGCD(X IN NUMBER,Y IN NUMBER )
RETURN NUMBER
IS
NR NUMBER;
BEGIN
IF N1>N2 then
NR:=N1;
DR:=N2;
else

42
NR:=N2;
DR:=N1;
END IF ;
WHILE(DR>0)
LOOP
R:=MOD(NR,DR);
NR:=DR;
DR:=R;
END LOOP;
RETURN NR;
END;
BEGIN
NR:=FINDGCD(N1,N2);
DBMS_OUTPUT.PUT_LINE('GCD :' || NR);
END;
/

8.Write a PL/SQL block that raises a custom exception when a number exceeds a
specific limit
DECLARE
LIMIT NUMBER:=100;
INPUT_NUM NUMBER:=&INPUT_NUM;
INVALID EXCEPTION;
43
BEGIN
IF INPUT_NUM >LIMIT then
RAISE INVALID;
ELSE
DBMS_OUTPUT.PUT_LINE('INPUT NUMBER '||INPUT_NUM||' LESS THAN LIMIT');
END IF;
EXCEPTION
WHEN
INVALID THEN
DBMS_OUTPUT.PUT_LINE('ERROR:LIMIT EXCEEDS');
END;
/

RESULT : The PL/SQL commands are created and successfully executed.

44
EXERCISE : 8
DATE : STORED PROCEDURE

AIM : To work with the Stored Procedure for creating university management system.

1.Write a stored procedure that retrieves all enrollments for a specific student based
on their StudentID, returning EnrollmentID, CourseID, and Status.

CREATE OR REPLACE PROCEDURE retrieve_data(stu_id IN VARCHAR2) AS


BEGIN
FOR r IN (SELECT enid, courseid, status
FROM enrollments
WHERE studentid = stu_id)
LOOP
DBMS_OUTPUT.PUT_LINE('Enrollment ID: ' || r.enid ||
', Course ID: ' || r.courseid ||
', Status: ' || r.status);
END LOOP;
END;
/

EXEC retrieve_data(‘S001’);

45
2. Write a stored procedure to insert a new enrollment record into the Enrollments
table.

CREATE OR REPLACE PROCEDURE insert_enrollments(


p_enid IN VARCHAR2,
p_studentid IN VARCHAR2,
p_courseid IN VARCHAR2,
p_endate IN DATE,
p_status IN VARCHAR2
) AS
BEGIN
INSERT INTO enrollments (enid, studentid, courseid, endate, status)
VALUES (p_enid, p_studentid, p_courseid, p_endate, p_status);
DBMS_OUTPUT.PUT_LINE('Enrollment record inserted: ' || p_enid);

COMMIT;
END;
/

EXEC insert into enrollments values( ‘E016’,’S011’,’C012’,TO_DATE(‘2024-11-


15’,’YYYY-MM-DD’).Active);

46
3. Create a stored procedure that updates the Grade for a specific enrollment based on
EnrollmentID. The procedure should accept the new grade and grade point as
parameters.

create or replace procedure up_grade(entid varchar2,gr varchar2,grpt varchar) is


BEGIN
update grades set grade = gr,gradepoint = grpt where enid=entid;
dbms_output.put_line('ROW HAS BEEN UPDATED');
end;
/

declare
entid varchar2(100):='&ENROLLMENTID';
gr varchar2(100) :='&GRADE';
grpt varchar2(100) :='&GRADEPOINT';
begin
up_grade(entid,gr,grpt);
end ; /

47
14.Write a PL/SQL block that calls a stored procedure to retrieve and display student
details (including DepartmentID) based on StudentID.
DECLARE
student_id VARCHAR2(20):='&studentid';
FIRST_NAME VARCHAR2(20);
E_MAIL VARCHAR2(20);
PHONE_NO VARCHAR2(20);
D_OB DATE;
DEPT_ID VARCHAR2(20);
procedure stu_details(student_id VARCHAR2) AS
BEGIN
select firstname,email,phoneno,dob,deptid into
FIRST_NAME,E_MAIL,PHONE_NO,D_OB,DEPT_ID FROM STUDENT where
studentid=student_id;dbms_output.put_line('student id :'||student_id|| ' , student name :'||
first_name||' , Email :'||e_mail||' , ph.number :'||phone_no||' , DOB :'||d_ob||' , Department
id :'||dept_id);
END;

BEGIN
stu_details(student_id);
end;
/

48
5. Create a PL/SQL block that takes an EnrollmentID and calls a stored procedure to
update the status of that enrollment.
CREATE OR REPLACE PROCEDURE up_enr(enr_id IN VARCHAR2 ) AS
BEGIN
UPDATE enrollments SET status = 'Completed'
WHERE enid = enr_id;
DBMS_OUTPUT.PUT_LINE('Status updated to Completed for Enrollment ID: ' ||
enr_id);
END;
/

RESULT : The stored procedure for the university management system is created and
successfully executed.
49
EXERCISE NO : 9
DATE: FUNCTIONS

AIM : To work with the functions for university management system.

1. Create a function that takes an InstructorID and returns the instructor's full name
and DepartmentName.

CREATE OR REPLACE FUNCTION get_instructor_info(


p_instructor_id VARCHAR2
) RETURN VARCHAR2 IS
full_name VARCHAR2(100);
deptname VARCHAR2(100);
result VARCHAR2(200);
BEGIN
SELECT i.firstname || ' ' || i.lastname, d.deptname
INTO full_name, deptname
FROM instructor i
JOIN department d ON i.deptid = d.deptid
WHERE i.insid = p_instructor_id;

result := 'Name: ' || full_name || ', Department: ' || deptname;


RETURN result;
END;
/

50
SELECT get_instructor_info('I001') AS instructor_info FROM dual;

2. Create a function that calculates the total number of credits a student is currently
enrolled in based on the StudentID.
CREATE OR REPLACE FUNCTION get_credits(stu_id IN VARCHAR2)
RETURN VARCHAR2 IS
total_credits INT;
BEGIN
SELECT SUM(c.credits)
INTO total_credits
FROM enrollments e
JOIN courses c ON e.courseid = c.courseid
WHERE e.studentid = stu_id;
RETURN total_credits;
END;
/

SELECT get_credits('S001') AS total_credits FROM dual;

51
3. Write a function that accepts a DepartmentID and returns the number of courses offered
in that department.
CREATE OR REPLACE FUNCTION no_courses(dept_id IN VARCHAR2)
RETURN VARCHAR2
IS
total_courses INT;
BEGIN
SELECT COUNT(*)
INTO total_courses
FROM courses
WHERE deptid = dept_id;

RETURN total_courses;
END;
/

SELECT no_courses('D01') AS total_courses FROM dual;

RESULT : The functions for the university management system is created and successfully
executed.

52
EXERCISE NO :10
DATE : CURSORS

AIM : To work with the cursors for university management system.

1.Create a PL/SQL block using an implicit cursor to update the status of enrollments
for students who haven't been active for more than a specified period (e.g., 6 months).
The block should mark their enrollment status as 'Inactive'. Include exception
handling also.

DECLARE
inactive_threshold DATE := ADD_MONTHS(SYSDATE, -6);
rows_updated NUMBER := 0;
BEGIN
UPDATE Enrollments
SET status = 'Inactive'
WHERE endate < inactive_threshold;
rows_updated := SQL%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE(rows_updated || ' enrollments marked as Inactive.');
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;
/

53
2. Write a PL/SQL block that uses an explicit cursor to find all departments with more
than a specified number of students enrolled in their courses. The cursor should fetch
the DepartmentID, DepartmentName, and the number of students enrolled. Include
exception handling for cases where no departments meet the criteria.

DECLARE
min_student_count NUMBER := 3;
CURSOR dept_cursor IS
SELECT d.deptid AS departmentid, d.deptname, COUNT(e.studentid) AS
student_count
FROM department d JOIN courses c ON d.deptid = c.deptid
JOIN enrollments e ON c.courseid = e.courseid
GROUP BY
d.deptid, d.deptname
HAVING COUNT(e.studentid) > min_student_count;
dept_record dept_cursor%ROWTYPE;
dept_found BOOLEAN := FALSE;
BEGIN
OPEN dept_cursor;
LOOP
FETCH dept_cursor INTO dept_record;
EXIT WHEN dept_cursor%NOTFOUND;
dept_found := TRUE;
DBMS_OUTPUT.PUT_LINE('Department ID: ' || dept_record.departmentid ||
', Department Name: ' || dept_record.deptname ||
', Student Count: ' || dept_record.student_count);
END LOOP;
CLOSE dept_cursor;

IF NOT dept_found THEN


54
RAISE_APPLICATION_ERROR(-20001, 'No departments have more than ' ||
min_student_count || ' students enrolled.');
END IF;

EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;
/

3. Create a PL/SQL block using an explicit cursor to list all students who have scored
below a specific grade point in any course, fetching the StudentID, FirstName,
LastName, CourseID, and Grade. Use exception handling to handle cases where no
students meet the grade criteria.

DECLARE
v_grade_threshold NUMBER := 7;
CURSOR student_cursor IS
SELECT
s.StudentID,
s.FirstName,
s.LastName,
e.CourseID,
g.Grade
55
FROM
Student s
JOIN Enrollments e ON s.StudentID = e.StudentID
JOIN Grades g ON e.EnID = g.EnID
WHERE
g.Gradepoint < v_grade_threshold;
student_record student_cursor%ROWTYPE;
v_no_students_found BOOLEAN := TRUE;

BEGIN
OPEN student_cursor;
LOOP
FETCH student_cursor INTO student_record;
EXIT WHEN student_cursor%NOTFOUND;
v_no_students_found := FALSE;
DBMS_OUTPUT.PUT_LINE('StudentID: ' || student_record.StudentID ||
', FirstName: ' || student_record.FirstName ||
', LastName: ' || student_record.LastName ||
', CourseID: ' || student_record.CourseID ||
', Grade: ' || student_record.Grade);
END LOOP;
CLOSE student_cursor;

IF v_no_students_found THEN
DBMS_OUTPUT.PUT_LINE('No students found with grade point below ' ||
v_grade_threshold);
END IF;

EXCEPTION
56
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;
/

RESULT : The cursors for the university management is created and successfully
executed.
57
EXERCISE NO : 11
DATE : TRIGGERS

AIM : To work with the Triggers for the university management system .

1. Write a trigger to automatically update the DepartmentHead in the Departments


table whenever a new instructor is assigned as the head of that department.

CREATE OR REPLACE TRIGGER update_department_head


AFTER INSERT ON Instructor
FOR EACH ROW
DECLARE
head_name VARCHAR2(50);
BEGIN
head_name := :NEW.firstname || ' ' || :NEW.lastname;

IF :NEW.DeptID IS NOT NULL THEN


UPDATE Department
SET DeptHead = head_name
WHERE DeptID = :NEW.DeptID;
END IF;
END;
/

58
2. Create a trigger to recalculate the Gradepoint for a student in the Grades table
whenever their grade is updated.

CREATE OR REPLACE TRIGGER update_gradepoint


BEFORE UPDATE OF grade ON grades
FOR EACH ROW
BEGIN
:NEW.gradepoint := CASE
WHEN :NEW.grade = 'O' THEN 10
WHEN :NEW.grade = 'A+' THEN 9
WHEN :NEW.grade = 'A' THEN 8
WHEN :NEW.grade = 'B+' THEN 7
WHEN :NEW.grade = 'B' THEN 6
ELSE 0
END;
END;
/

59
3.Develop a trigger to ensure that when changing the instructor for a course in the
Courses table, the new InstructorID must exist in the Instructors table. If it does not,
raise an exception.

CREATE OR REPLACE TRIGGER validate_instructor


BEFORE UPDATE OF insid ON Courses
FOR EACH ROW
DECLARE
v_count NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_count
FROM Instructor
WHERE insid = :NEW.insid;

IF v_count = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'InsID does not exist in the Instructors
table.');
60
END IF;
END;
/

RESULT : The triggers for the university management system is created and successfully
executed.

61
EXERCISE NO: 12
DATE: TRANSACTION

AIM :To work with the transaction / data control language and normalization for university
management system.

1.In a transaction where: A new instructor is assigned to a course in the Courses table. The
instructor’s department is updated in the Departments table. Use a savepoint after step 1. If
an error occurs while updating the department, roll back to the savepoint to cancel the
course assignment for the instructor.

BEGIN
UPDATE Courses
SET insid = 'I011'
WHERE courseid = 'C003';

SAVEPOINT assign_instructor;

UPDATE Departments
SET deptname = 'Economics'
WHERE deptid = (SELECT deptid FROM Instructor WHERE insid = 'I011');
DBMS_OUTPUT.PUT_LINE('Transaction completed successfully !!');

commit;

EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO assign_instructor;
DBMS_OUTPUT.PUT_LINE('Transaction failed: ' || SQLERRM);

62
COMMIT;
END;
/

2.Assume Functional Dependencies for each table. Discuss whether each table is in 3NF. If
either is not in 3NF, suggest how it could be decomposed to satisfy 3NF.

Student Table :
 Schema:
STUDENTID, FIRSTNAME, LASTNAME, EMAIL, PHONENO, DOB, DEPTID
 Functional dependencies :
STUDENTID→FIRSTNAME, LASTNAME, EMAIL, PHONENO, DOB, DEPTID
EMAIL→STUDENTID
 Candidate key :
STUDENTID , EMAIL

 3NF Condition :
No Partial Dependencies: All non-key attributes depend fully on STUDENTID.
No Transitive Dependencies: PHONENO and DEPTID are directly dependent on
STUDENTID and not on another non-prime attribute.
 CONCLUSION :
Student Table is in 3NF.

Courses Table :
 Schema :
COURSEID, COURSENAME, CREDITS, DEPTID, INSID, ENDDATE.
 Functional dependencies :

63
COURSEID→COURSENAME, CREDITS, DEPTID, INSID, ENDDATE.
INSID→DEPTID.
DEPTID→DEPARTMENTNAME.
 Candidate key :
COURSE ID

 3NF Condition :
No Partial Dependencies: All non-key attributes depend fully on COURSEID.
Transitive Dependency: INSID→DEPTID, which leads to a transitive dependency
COURSEID→INSID→DEPTID. This violates 3NF since DEPTID depends on
INSID and not directly on COURSEID.

 Decomposition Needed :
Create a new table for instructors to store the relationship between INSID and
DEPTID
Instructors: INSID, DEPTID

Instructors table :
 Schema :
INSID, FIRSTNAME, LASTNAME, EMAIL, PHONENO, DEPTID
 Functional dependencies :
INSID→FIRSTNAME, LASTNAME, EMAIL, PHONENO, DEPTID
EMAIL→INSID
DEPTID→DEPARTMENTNAME.
 Candidate key :
INSID

 3NF Condition:
No Partial Dependencies: All non-key attributes depend fully on INSID.
No Transitive Dependencies: DEPTID does not transitivity in this table.

 Conclusion :
The Instructor table is in 3NF.

64
Enrollments Table :
 Schema :
ENID, STUDENTID, COURSEID, ENDATE, STATUS
 Functional dependencies :
ENID→STUDENTID, COURSEID, ENDATE, STATUS
STUDENTID, COURSEID→ENDATE, STATUS
COURSEID→DEPTID
 Candidate key :
ENID

 3NF Condition:
No Partial Dependencies: All non-key attributes depend fully on ENID, as it is the
unique identifier for the table.
No Transitive Dependencies: No attribute depends on a non-prime attribute through
transitivity. Dependencies such as COURSEID→DEPTIDare managed in the Courses
table and are not directly part of this table.
 Conclusion :
The Enrollments table is in 3NF

Departments Table :
 Schema :
DEPTID, DEPTNAME, DEPTHEAD
 Functional dependencies :
DEPTID→DEPTNAME, DEPTHEAD
DEPTNAME→DEPTHEAD
 Candidate key :
DEPTID

 3NF Condition:
No Partial Dependencies: All non-key attributes depend fully on DEPTID.
Transitive Dependency: DEPTID→DEPTNAME→DEPTHEAD.

 Decomposition Needed :
Create a new table to separate department and department head information.
Departments: DEPTID, DEPTNAME
65
DepartmentHeads: DEPTNAME, DEPTHEAD.

Grades table :
 Schema :
GRADE, ENID, GRADEPOINT.

 Functional dependencies :
ENID→GRADE, GRADEPOINT
GRADE→GRADEPOINT

 Candidate key :
ENID

 3NF Condition:
No Partial Dependencies: All non-key attributes depend fully on ENID.
Transitive Dependency: ENID→GRADE→GRADEPOINT.
 Decomposition Needed :
Create a separate table to store the relationship between grades and grade points:
GradesReference: GRADE, GRADEPOINT

RESULT : Transaction was created and successfully executed for university management
system.

66
EXERCISE NO: 13
DATE : MONGODB – CRUD OPERATIONS

AIM : To work with the MONGO DATABASE by creating a university database using a
crud operations.

1.Write a query to insert a new student into the students collection with fields for
name, student ID, major, and enrollment year.
db.students.insertOne({ name:"Revaan",studentID:"510057",Major :"
computerscience",enrollment_year:"2024"});

2.Create a query to insert multiple new students into the students collection at once.
db.students.insertMany([ { name:
"saravanan",studentID:'510056',Major:'mechanical',enrollment_year: '2024'},
{ name:'madhu',studentID:'510058',major:'civil',enrollment_year:'2024'},
{ name:"suji",studentID:'510059',Major:'electronics',enrollment_year:'2024'},
{ name:'kevin',studentID:'510060',Major:'information technology',enrollment_year: '2024'},
{ name:'yuvaraj',studentID:'510061',Major:'automobile',enrollment_year:'2024'},
{name:'ragul',studentID:'510062',Major:'robotics',enrollment_year:'2024'} ]);

67
inserting value :

68
3. Write a query to find a student by their student ID.
db.students.find({ studentID:'510057'})

4. Create a query to fetch all students enrolled in a specific department (e.g.,


"Computer Science")

db.students.find({ department:'computer technology dept'})

69
5. Implement a query to sort students by their enrollment year in descending order.

db.students.find().sort({enrollment_year:-1})

70
71
72
6. Write a query to limit the results to the first 10 students in the students collection.
db.students.find().limit(10)

73
7. Write a query to update the department of a specific student using their student ID.
db.students.updateOne({ studentID:'510062'},{$set:{department:'Auto dept'}} )
74
Initial value :

Updated value :

Note :
Updation of Major is done because of the departement gets updated.

8. Create a query to update the enrollment year for a specific student.


db.students.updateOne({name:'shyaam'},{$set:{enrollment_year:'2021'}}

75
Initial value :

Updated value :

9. Write a query to delete a student from the students collection using their student
ID.
db.students.deleteOne({ studentID:'510066'})

Deleted value :

10. Write a query to find and list all courses offered by a specific department.
Course table:

76
db.courses.find({departmentID:'D02'})

RESULT : The crud operations for the university management database in MONGODB
was created and successfully executed.

77

You might also like