Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
25 views41 pages

Dbms Manual

The document outlines the Database Management System Laboratory manual for BCS403 at Visvesvaraya Technological University, detailing the course structure, objectives, and practical components. It includes a series of experiments for students to execute, covering SQL commands, database design, and NoSQL operations. Additionally, it specifies assessment methods and learning resources for the academic year 2023-2024.

Uploaded by

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

Dbms Manual

The document outlines the Database Management System Laboratory manual for BCS403 at Visvesvaraya Technological University, detailing the course structure, objectives, and practical components. It includes a series of experiments for students to execute, covering SQL commands, database design, and NoSQL operations. Additionally, it specifies assessment methods and learning resources for the academic year 2023-2024.

Uploaded by

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

.

VISVESVARAYA TECHNOLOGICAL UNIVERSITY


JNANA SANGAMA, BELGAVI-590018, KARNATAKA

DATABASE MANAGEMENT SYSTEM LABORATORY


BCS403

Manual Prepared by
Ranjith V, Assistant Professor
Veena M S, Assistant
Dr. Manjunath R, AssistantProfessor
Professor,
Tejaswini Krishnamurthy, Assistant Professor

Department of Computer Science & Engineering


R.R. Institute of Technology

Academic year 2023-2024


PKM Educational Trust ®

R. R. Institute of Technology
Affiliated to VTU Belgaum and Approved by AICTE, New Delhi ,Recognized by Govt. of Karnataka
Accredited by NAAC with ‘A+’
Raja Reddy Layout, Chikkabanavara, Bengaluru – 560 090

Department of Computer Science & Engineering

College Vision "To be a Premier globally recognized Institute with ensuring academic excellence, Innovation
and fostering Research in the field of Engineering"
College Mission • To consistently strive for Academic Excellence
• To promote collaborative Research & Innovation
• To create holistic teaching learning environment that build ethically sound manpower
who contribute to the stake holders operating at Global environment

Department To arise as an excellent learning center in the field of Computer Science & Engineering by fostering a
Vision skilled, innovative professionals to build a strong nation.

Department • To provide a conceptual foundation that caters the career required to adopt for changing
Mission technology in computer science.
• To bridge the gap between academics and the latest tools, technologies in the area of hardware
and software.
• To set out co-curricular open doors for student’s participation in advancements and recent
trends.
• To explore the potential and excel the students towards research to attain Novelty.

Program PEO1: Proficient to recognize contemporary issues and provide solutions using broad
Educational
knowledge of computer science.
Objectives
(PEOs) PEO2: Ability to plan, analyze, design, evolve project implementing capabilities and skills in
IT industry.
PEO3: Drive to adapt new computing technologies lifelong to acquire professional greatness.
PEO4: Possess professional, ethical, social responsibilities, communicational skills and team
work needed for a successful professional carrier.

Program PSO1: Apply the software practices, principals to design and analyse the complex computer based
Specific system.
Outcomes
(PSOs) PSO2: Design, implement and validate system software and application software to the various societal
needs.
PKM Educational Trust ®

R. R. Institute of Technology
Affiliated to VTU Belgaum and Approved by AICTE, New Delhi ,Recognized by Govt. of Karnataka
Accredited by NAAC with ‘A+’
Raja Reddy Layout, Chikkabanavara, Bengaluru – 560 090

Department of Computer Science & Engineering

Program Outcomes (POs)


PO1 Engineering Knowledge: Apply knowledge of mathematics and science, with fundamentals of
Computer Science & Engineering to be able to solve complex engineering problems related to CSE.
PO2 Problem Analysis: Identify, Formulate, review research literature and analyse complex
engineering problems related to CSE and reaching substantiated conclusions using first principles
of mathematics, natural sciences and engineering sciences.
PO3 Design/Development of Solutions: Design solutions for complex engineering problems related to
CSE and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety and the cultural societal and environmental
considerations.
PO4 Conduct Investigations of Complex Problems: Use research–based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5 Modern Tool Usage: Create, Select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modelling to computer science related complex
engineering activities with an understanding of the limitations.
PO6 The Engineer and Society: Apply Reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
CSE professional engineering practice.
PO7 Environment and Sustainability: Understand the impact of the CSE professional engineering
solutions in societal and environmental contexts and demonstrate the knowledge of, and need for
sustainable development.
PO8 Ethics: Apply Ethical Principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO9 Individual and Team Work: Function effectively as an individual and as a member or leader in
diverse teams and in multidisciplinary Settings.
PO10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large such as able to comprehend and with write
effective reports and design documentation, make effective presentations and give and receive clear
instructions.
PO11 Project Management and Finance: Demonstrate knowledge and understanding of the
engineering management principles and apply these to one’s own work, as a member and leader in
a team, to manage projects and in multi-disciplinary environments.
PO12 Life-Long Learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning the broadest context of technological change.
[Type here] [Type here] [Type here]

PRACTICAL COMPONENT OF IPCC DBMS (BCS403)


Sl.NO Experiments
1 Create a table called Employee & execute the following.
Employee(EMPNO,ENAME,JOB, MANAGER_NO, SAL, COMMISSION)
1. Create a user and grant all permissions to theuser.
2. Insert the any three records in the employee table contains attributes
EMPNO,ENAME JOB, MANAGER_NO, SAL, COMMISSION and use rollback.
Check the result.
3. Add primary key constraint and not null constraint to the employee table.
4. Insert null values to the employee table and verify the result.
2 Create a table called Employee that contain attributes EMPNO,ENAME,JOB, MGR,SAL &
execute the following.
1. Add a column commission with domain to the Employeetable.
2. Insert any five records into the table.
3. Update the column details of job
4. Rename the column of Employ table using alter command.
5. Delete the employee whose Empno is 105.
3 Queries using aggregate functions(COUNT,AVG,MIN,MAX,SUM),Group by,Orderby.
Employee(E_id, E_name, Age, Salary)
1. Create Employee table containing all Records E_id, E_name, Age, Salary.
2. Count number of employee names from employeetable
3. Find the Maximum age from employee table.
4. Find the Minimum age from employeetable.
5. Find salaries of employee in Ascending Order.
6. Find grouped salaries of employees.
4 Create a row level trigger for the customers table that would fire for INSERT or UPDATE or
DELETE operations performed on the CUSTOMERS table. This trigger will display the
salary difference between the old & new Salary.
CUSTOMERS(ID,NAME,AGE,ADDRESS,SALARY)
5 Create cursor for Employee table & extract the values from the table. Declare the variables
,Open the cursor & extrct the values from the cursor. Close the cursor.
Employee(E_id, E_name, Age, Salary)
6 Write a PL/SQL block of code using parameterized Cursor, that will merge the data available
in the newly created table N_RollCall with the data available in the table O_RollCall. If the
data in the first table already exist in the second table then that data should be skipped.
7 Install an Open Source NoSQL Data base MangoDB & perform basic CRUD(Create, Read,
Update & Delete) operations. Execute MangoDB basic Queries using CRUD operations.
Course outcomes (Course Skill Set):
At the end of the course, the student will be able to:
● Describe the basic elements of a relational database management system
● Design entity relationship for the given scenario.
● Apply various Structured Query Language (SQL) statements for database manipulation.
● Analyse various normalization forms for the given application.
● Develop database applications for the given real world problem.
● Understand the concepts related to NoSQL databases.
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The minimum
[Type here] [Type here] [Type here]

passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the SEE minimum passing mark is
35% of the maximum marks (18 out of 50 marks). A student shall be deemed to have satisfied the academic requirements
and earned the credits allotted to each subject/ course if the student secures a minimum of 40% (40 marks out of 100) in the
sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken together.
CIE for the theory component of the IPCC (maximum marks 50)
● IPCC means practical portion integrated with the theory of the course.
● CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.
● 25 marks for the theory component are split into 15 marks for two Internal Assessment Tests (Two Tests, each of 15
Marks with 01-hour duration, are to be conducted) and 10 marks for other assessment methods mentioned in 22OB4.2.
The first test at the end of 40-50% coverage of the syllabus and the second test after covering 85-90% of the syllabus.
● Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the theory
component of IPCC (that is for 25 marks).
● The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC.
CIE for the practical component of the IPCC
● 15 marks for the conduction of the experiment and preparation of laboratory record, and 10 marks for the test to be
conducted after the completion of all the laboratory sessions.
● On completion of every experiment/program in the laboratory, the students shall be evaluated including viva-voce and
marks shall be awarded on the same day.
● The CIE marks awarded in the case of the Practical component shall be based on the continuous evaluation of the
laboratory report. Each experiment report can be evaluated for 10 marks. Marks of all experiments’ write-ups are added
and scaled down to 15 marks.
● The laboratory test (duration 02/03 hours) after completion of all the experiments shall be conducted for 50 marks
and scaled down to 10 marks.
● Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory component of IPCC
for 25 marks.
● The student has to secure 40% of 25 marks to qualify in the CIE of the practical component of the IPCC.
SEE for IPCC
Theory SEE will be conducted by University as per the scheduled timetable, with common question papers for the course
(duration 03 hours)
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a maximum of 3 sub-
questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.
4. Marks scoredby the student shall be proportionally scaled down to 50 Marks
The theory portion of the IPCC shall be for both CIE and SEE, whereas the practical portion will have a CIE
component only. Questions mentioned in the SEE paper may include questions from the practical component.

Suggested Learning Resources:


Text Books:
1. Fundamentals of Database Systems, Ramez Elmasri and Shamkant B. Navathe, 7th Edition, 2017, Pearson.
2. Database management systems, Ramakrishnan, and Gehrke, 3rd Edition, 2014, McGraw Hill
Activity Based Learning (Suggested Activities in Class)/ Practical Based learning
Mini Project:
• Project Based Learning
BCS403 DATABASE MANAGEMENT SYSTEM

1. Create a table called Employee & execute the following.


Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION)
1. Create a user and grant all permissions to the user.
2. Insert the any three records in the employee table contains attributes
EMPNO, ENAME JOB, MANAGER_NO, SAL, COMMISSION and use rollback.
Check the result.
3. Add primary key constraint and not null constraint to the employee table.
4. Insert null values to the employee table and verify the result.

ALTER SESSION SET "_ORACLE_SCRIPT" = TRUE;

1. Create a user and grant all permissions to the user.

CREATE USER ABCD IDENTIFIED BY XYZ;


GRANT ALL PRIVILEGES TO ABCD;

TABLE CREATION

CREATE TABLE Employee (


EMPNO INT,
ENAME VARCHAR (15),
JOB VARCHAR (15),
MANAGER_NO INT,
SAL DECIMAL (10, 2),
COMMISSION DECIMAL (10, 2)
);

TABLE DESCRIPTION

1
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

2. Insert the any three records in the employee table contains attributes
EMPNO, ENAME JOB, MANAGER_NO, SAL, COMMISSION and use rollback.
Check the result.

INSERTING VALUES INTO TABLE

INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION) VALUES (1, 'Kavana
Shetty', 'Manager', NULL, 50000.00, 1000.00);

INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION) VALUES (2, 'Ram
Charan', 'Developer', 1, 40000.00, NULL);

INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION) VALUES (3, 'Honey
Singh', 'Salesperson', 2, 30000.00, 500.00);

SELECT * FROM EMPLOYEE;

ROLLBACK;

3. Add primary key constraint and not null constraint to the employee table.

ALTER TABLE EMPLOYEE ADD CONSTRAINT pk_EMPLOYEE PRIMARY KEY(EMPNO);


ALTER TABLE EMPLOYEE MODIFY ENAME NOT NULL;

TABLE DESCRIPTION

2
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

4. Insert null values to the employee table and verify the result.

INSERT INTO Employee VALUES (NULL, NULL, NULL, NULL, NULL, NULL);

3
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

2. Create a table called Employee that contain attributes EMPNO, ENAME, JOB, MGR, SAL
& execute the following.
1. Add a column commission with domain to the Employee Table.
2. Insert any five records into the table.
3. Update the column details of job
4. Rename the column of Employ table using alter command.
5. Delete the employee whose EMPNO is 105.

TABLE CREATION

CREATE TABLE Employee (


EMPNO INT,
ENAME VARCHAR(15),
JOB VARCHAR(20),
MGR INT,
SAL DECIMAL(10, 2)
);

TABLE DESCRIPTIONS

ALTER TABLE Employee ADD COMMISSION DECIMAL(10, 2);

INSERT INTO Employee VALUES (101, 'Radha Bai', 'Manager', NULL, 5000.00, 1000.00);
INSERT INTO Employee VALUES (102, 'Krishna Kumar', 'Developer', 101, 4000.00, NULL);
INSERT INTO Employee VALUES (103, 'Abdul Sattar', 'Salesperson', 102, 3000.00, 500.00);
INSERT INTO Employee VALUES (104, 'Bob Johnson', 'Accountant', 101, 4500.00, NULL);
INSERT INTO Employee VALUES (105, 'Amartya Sen', 'HR Manager', 101, 4800.00, 800.00);

4
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

UPDATE Employee SET JOB = 'Senior Developer' WHERE EMPNO = 102;

ALTER TABLE Employee RENAME COLUMN MGR TO MANAGER_ID;

DELETE FROM Employee WHERE EMPNO = 105;

5
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

3.Queries using aggregate functions (COUNT, AVG, MIN, MAX, SUM), Group by, Order by.
Employee (E_id, E_name, Age, Salary)
1. Create Employee table containing all Records E_id, E_name, Age, Salary.
2. Count number of employee names from employee table.
3. Find the Maximum age from employee table.
4. Find the Minimum age from employee table.
5. Find salaries of employee in Ascending Order.
6. Find grouped salaries of employees.

CREATE TABLE Employee (


E_id INT PRIMARY KEY,
E_name VARCHAR (25),
Age INT,
Salary DECIMAL (10, 2)
);

INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (1, 'Samarth', 30, 50000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (2, 'Ramesh Kumar', 25, 45000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (3, 'Seema Banu', 35, 60000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (4, 'Dennis Anil', 28, 52000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (5, 'Rehman Khan', 32, 58000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (6, 'Pavan Gowda', 40, 70000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (7, 'Shruthi Bhat', 27, 48000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (8, 'Sandesh Yadav', 29, 52000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (9, 'Vikram Acharya', 33, 62000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (10, 'Praveen Bellad', 26, 46000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (11, 'Sophia Mary', 31, 55000.00);
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES (12, 'Darshan Desai', 34, 62000.00);

6
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

SELECT COUNT(E_name) AS Total_Employees FROM Employee;

SELECT MAX(Age) AS Max_Age FROM Employee;

SELECT MIN(Age) AS Min_Age FROM Employee;

SELECT E_name, Salary FROM Employee ORDER BY Salary ASC;

7
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

SELECT Salary, COUNT (*) AS Employee_Count FROM Employee GROUP BY Salary;

8
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

4.Create a row level trigger for the customers table that would fire for INSERT or UPDATE or
DELETE operations performed on the CUSTOMERS table. This trigger will display the
salary difference between the old & new Salary.
CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)

CREATE TABLE CUSTOMERS (


id INT PRIMARY KEY,
name VARCHAR(10),
age INT,
address VARCHAR(15),
salary DECIMAL(10, 2)
);

SET SERVEROUTPUT ON;

CREATE OR REPLACE TRIGGER salary_difference_trigger


AFTER INSERT OR UPDATE OR DELETE ON customers
FOR EACH ROW
DECLARE
salary_diff NUMBER;
BEGIN
IF INSERTING OR UPDATING THEN
salary_diff := :new.salary - NVL(:old.salary, 0);
ELSE
salary_diff := -1 * NVL(:old.salary, 0); -- For DELETE operation
END IF;
DBMS_OUTPUT.PUT_LINE('Old salary: ' || :OLD.salary);
DBMS_OUTPUT.PUT_LINE('New salary: ' || :NEW.salary);
DBMS_OUTPUT.PUT_LINE('Salary difference: ' || salary_diff);
END;
/

9
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

INSERT INTO CUSTOMERS (ID,NAME, AGE, ADDRESS, SALARY) VALUES(1, 'John Doe', 30, '123 Elm
Street', 50000.00);

UPDATE customers SET salary = 55000.00 WHERE id = 1;

DELETE FROM customers WHERE id = 1;

10
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

5.Create cursor for Employee table & extract the values from the table. Declare the variables
,Open the cursor & extract the values from the cursor. Close the cursor.
Employee(E_id, E_name, Age, Salary)

CREATE TABLE Employee (


E_id INT PRIMARY KEY,
E_name VARCHAR(20),
Age INT,
Salary DECIMAL(10, 2)
);

INSERT INTO Employee VALUES (1, 'Samarth', 30, 50000.00);


INSERT INTO Employee VALUES (2, 'Ramesh Kumar', 25, 45000.00);
INSERT INTO Employee VALUES (3, 'Seema Banu', 35, 62000.00);
INSERT INTO Employee VALUES (4, 'Dennis Anil', 28, 52000.00);
INSERT INTO Employee VALUES (5, 'Rehman Khan', 32, 58000.00);

DECLARE
v_id Employee.E_id%TYPE;
v_name Employee.E_name%TYPE;
v_age Employee.Age%TYPE;
v_salary Employee.Salary%TYPE;

CURSOR emp_cursor IS
SELECT E_id, E_name, Age, Salary FROM Employee;

BEGIN

OPEN emp_cursor;
11
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
LOOP

FETCH emp_cursor INTO v_id, v_name, v_age, v_salary;


EXIT WHEN emp_cursor%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_id || ', Name: ' || v_name || ', Age: ' || v_age || ', Salary: ' || v_salary);
END LOOP;

CLOSE emp_cursor;
END;
/

12
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

6.Write a PL/SQL block of code using parameterized Cursor, that will merge the data available
in the newly created table N_RollCall with the data available in the table O_RollCall. If the
data in the first table already exist in the second table then that data should be skipped.

CREATE TABLE O_RollCall (


student_id INT PRIMARY KEY,
student_name VARCHAR(20),
birth_date DATE
);

CREATE TABLE N_RollCall (


student_id INT PRIMARY KEY,
student_name VARCHAR(20),
birth_date DATE
);

INSERT INTO O_RollCall values (1, 'Shivanna', TO_DATE('1995-08-15', 'YYYY-MM-DD'));


INSERT INTO O_RollCall values (3, 'Cheluva', TO_DATE('1990-12-10', 'YYYY-MM-DD'));

13
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

INSERT INTO N_RollCall values (1, 'Shivanna', TO_DATE('1995-08-15', 'YYYY-MM-DD'));


INSERT INTO N_RollCall values (2, 'Bhadramma', TO_DATE('1998-03-22', 'YYYY-MM-DD'));
INSERT INTO N_RollCall values (3, 'Cheluva', TO_DATE('1990-12-10', 'YYYY-MM-DD'));
INSERT INTO N_RollCall values (4, 'Devendra', TO_DATE('2000-05-18', 'YYYY-MM-DD'));
INSERT INTO N_RollCall values (5, 'Eshwar', TO_DATE('1997-09-03', 'YYYY-MM-DD'));

CREATE OR REPLACE PROCEDURE merge_rollcall_data IS


-- Declare variables
n_id N_RollCall.student_id%TYPE;
n_name N_RollCall.student_name%TYPE;
n_birth_date N_RollCall.birth_date%TYPE;

-- Declare cursor for N_RollCall table


CURSOR n_cursor IS
SELECT student_id, student_name, birth_date
FROM N_RollCall;

-- Variable to handle end of cursor


done BOOLEAN := FALSE;

BEGIN
-- Open the cursor
OPEN n_cursor;

-- Start looping through cursor results


LOOP
-- Fetch data from cursor into variables
FETCH n_cursor INTO n_id, n_name, n_birth_date;

-- Check if no more rows to fetch


IF n_cursor%NOTFOUND THEN

14
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
done := TRUE;
END IF;

-- Exit loop if done


EXIT WHEN done;

-- Check if the data already exists in O_RollCall


BEGIN
SELECT student_id INTO n_id
FROM O_RollCall
WHERE student_id = n_id;

-- If record exists, skip insertion


DBMS_OUTPUT.PUT_LINE('Record with student_id ' || n_id || ' already exists in O_RollCall. Skipping...');
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- Insert the record into O_RollCall if not exists
INSERT INTO O_RollCall (student_id, student_name, birth_date)
VALUES (n_id, n_name, n_birth_date);

DBMS_OUTPUT.PUT_LINE('Inserted record with student_id ' || n_id || ' into O_RollCall.');


END;
END LOOP;

-- Close the cursor


CLOSE n_cursor;
END;
/
exec merge_rollcall_data;

SELECT * FROM O_RollCall;

15
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

7. Install an Open Source NoSQL Data base MangoDB & perform basic CRUD(Create,
Read,Update & Delete) operations. Execute MangoDB basic Queries using CRUD operations.

Install an Open Source NoSQL Data base MangoDB & perform basic
CRUD(Create, Read,Update & Delete) operations. Execute MangoDB basic
Queries using CRUD operations.

How to Install and Configure MongoDB ?


MongoDB is a popular NoSQL database offering flexibility, scalability, and ease of use. Installing and
configuring MongoDB in Ubuntu is a straightforward process, but it requires careful attention to detail
to ensure a smooth setup.
In this guide, we’ll learn how to install and configure MongoDB in Ubuntu. We’ll walk you through
each step, from installation to configuration, enabling you to harness the power of MongoDB on your
Ubuntu system.
Let’s look at the requirements for installing MongoDB in Ubuntu.

Steps to Install and Configure MongoDB in Ubuntu

MongoDB can be installed on Ubuntu with the use of the following commands. These commands are
easy to run on the terminal and make the installation process handy. Follow the steps given below to
install MongoDB:

Step 1: First you need to update and upgrade your system repository to install MongoDB. Type the
following command in your terminal and then press Enter.

sudo apt update && sudo apt upgrade

16
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

Step 2: Now, install the MongoDB package using ‘apt ‘. Type the following command and press
Enter.
sudo apt install -y mongodb

Step 3: Check the service status for MongoDB with the help of following command:
sudo systemctl status mongodb

systemctl verifies that MongoDB server is up and running.


17
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

Step 4: Now check if the installation process is done correctly and everything is working fine. Go
through the following command:
mongo --eval 'db.runCommand({ connectionStatus: 1 })'

the value “1” in ok field indicates that the server is working properly with no errors.

Step 5: MongoDB services can be started and stopped with the use of following commands: To stop
running the MongoDB service, use command:

sudo systemctl stop mongodb

MongoDB service has been stopped and can be checked by using the status command:

sudo systemctl status mongodb

18
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

As it can be seen that the service has stopped, to start the service we can use :
sudo systemctl start mongodb

Step 6: Accessing the MongoDB Shell


MongoDB provides a command-line interface called the MongoDB shell, which allows you to
interact with the database.
To access the MongoDB shell, simply type the following command in your terminal:
mongo
You are now connected to the MongoDB server, and you can start executing commands
to create databases, collections, and documents.
CRUD Operations:

1. Create (Insert)
To create or insert data into a MongoDB collection, you use the insertOne() or
19
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
insertMany() methods.
Insert a single document:
db.collection('yourCollection').insertOne({ key: value });
Insert multiple documents:
db.collection('yourCollection').insertMany([
{ key1: value1 },
{ key2: value2 },
// more documents
]);

2. Read (Query)
To read or retrieve data from a MongoDB collection, you use the find() method.
Find all documents:
db.collection('yourCollection').find();
Find documents with a specific condition:
db.collection('yourCollection').find({ key: value });

3. Update
To update existing documents in a MongoDB collection, you use the updateOne() or updateMany()
methods.
Update a single document:
db.collection('yourCollection').updateOne(
{ key: value }, // filter
{ $set: { newField: newValue } } // update operation
);
Update multiple documents:
db.collection('yourCollection').updateMany(
{ key: value }, // filter
{ $set: { newField: newValue } } // update operation
);

4. Delete
To delete documents from a MongoDB collection, you use the deleteOne() or deleteMany() methods.
Delete a single document:
db.collection('yourCollection').deleteOne({ key: value });
Delete multiple documents:
db.collection('yourCollection').deleteMany({ key: value });

20
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
VIVA-QUESTIONS

1. What is data?
Data is a collection of information gathered by observations, measurements,
research or analysis.

2. What is database?
A database is an electronically stored, systematic collection of data. It can contain
any type of data, including words, numbers, images, videos, and files.

3. What is DBMS?
Database Management Systems (DBMS) are software systems used to store,
retrieve, and run queries on data.

4. What is a Database system?


A database is an organized collection of structured information, or data, typically
stored electronically in a computer system.

5. What are the advantages of DBMS?


The advantages of database management include improved data integrity,
consistency, and security, efficient data access and sharing, and reduced data
redundancy and inconsistency.

6. What is relational database?


A relational database is a collection of information that organizes data in
predefined relationships where data is stored in one or more tables (or "relations")
of columns and rows.

7. What is Table?
A table is an arrangement of data in rows and columns, or possibly in a more
complex structure.

8. What is a Tuple?
A tuple is an ordered sequence of values. The values can be repeated, but their
number is always finite.

9. What is Columns?
column or pillar in architecture and structural engineering is a structural element
that transmits, through compression, the weight of the structure above to other
structural elements below.
21
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

10. What is a query?


A query is a question or a request for information expressed in a formal manner.

11.What is an Attribute ?
A quality, character, or characteristic ascribed to someone or something has leadership attributes.

12.What is Single valued Attributes ?


Single-valued attributes Single-valued attributes accept only one value. For single-valued attributes,
the syntax is: attribute = value attribute = "value with spaces" Multi-valued attributes.

13.What is Multi valued Attributes?


A multivalued attribute of an entity is an attribute that can have more than one value associated with
the key of the entity.

14.What is Compound /Composite Attribute?


A multivalued attribute of an entity is an attribute that can have more than one value associated with
the key of the entity.

15.What is Simple/Atomic Attributes?


A simple, or atomic, attribute is one that cannot be decomposed into meaningful components.

16. What is Sorted Attribute?


Stored attributes are those attributes that are stored in the physical database for e.g date of birth.

17.What is Derived Attribute ?


A derived attribute is one that can be figured out from other information. An example is "age". A
person's age can be derived from date of birth.

18.What is Complex Attributes?


Complex attributes are formed by grouping together the attributes of composite and multi-valued
attributes.

19.What is Key Attribute ?


In DBMS, key attributes refer to the specific fields or columns in a table that are used to uniquely
identify each record in the table.

20.What is Non Key Attributes ?


22
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
The values of a primary key cannot be duplicated. Non-prime (non-key) attributes are those that are
not the primary key attributes.

21.What is a primary key?


A primary key is a column whose values uniquely identify every row in a table.

22.What are the conditions for a field to be a primary key?

• No two rows can have the same primary key value.


• Every row must have a primary key value.
• The primary key field cannot be null.
• Value in a primary key column can never be modified or updated, if any
foreign key refers to that primary key.

23. What is a Foreign Key ?


When a "one" table's primary key field is added to a related "many" table in order to create the common
field which relates the two tables, it is called a foreign key in the "many" table.
For example, the salary of an employee is stored in salary table. The relation is established via foreign
key column “Employee_ID_Ref” which refers “Employee_ID” field in the Employee table.

24.What is Super Key?


A set of attributes (one or more) that collectively identifies an entity in an entity set.

25.What is Candidate Key


A minimal super key is called a candidate key. An entity set may have more than one candidate key.

26.What is a query?
A query with respect to DBMS relates to user commands that are used to interact with a data base.
The query language can be classified into data definition language and data manipulation language.

27. How do you perform CRUD operations create, read, update, delete MongoDB?
MongoDB CRUD Operation
The Create operation is used to insert new documents in the MongoDB database.
The Read operation is used to query a document in the database.
The Update operation is used to modify existing documents in the database.
The Delete operation is used to remove documents in the database.

23
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
28. What are the CRUD operations in NoSQL database?
CRUD is the acronym for CREATE, READ, UPDATE and DELETE. These terms describe the
four essential operations for creating and managing persistent data elements, mainly in relational and
NoSQL databases.

29. How to update in CRUD operations?


You can perform update, insert and delete operation in the Grid. While performing these operations,
the corresponding event is invoked. In that event SQL query is used to update the database. The events
for performing CRUD operation are declared.

30. How can we create updating and deleting documents in MongoDB?


The MongoDB shell provides the following methods to update documents in a collection:
1. To update a single document, use db. collection. updateOne() .
2. To update multiple documents, use db. collection. updateMany() .
3. To replace a document, use db. collection. replaceOne() .
4. What is the full form of CRUD in MongoDB?
The basic methods of interacting with a MongoDB server are called CRUD operations. CRUD stands
for Create, Read, Update, and Delete. These CRUD methods are the primary ways you will manage
the data in your databases.

31. What are the CRUD methods in REST API?


CRUD stands for Create, Read, Update, and Delete. These are the four fundamental operations of
persistent storage. In the context of RESTful APIs , they correspond to the HTTP methods POST,
GET, PUT/PATCH, and DELETE.

32. How to create a collection in MongoDB?


Several ways can be employed to create and remove collections in MongoDB. Of which one way is
by using db. Create Collection (name, options). MongoDB creates a collection for an inserted
command automatically if no similar collection already exists in the MongoDB database.

24
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

EXTRA QUERIES

Consider the following schema for Order Database: SALESMAN (Salesman_id, Name, City,
Commission) CUSTOMER (Customer_id, Cust_Name, City, Grade, Salesman_id) ORDERS
(Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id) Write SQL queries to 1. Count
the customers with grades above Bangalore’s average. 2. Find the name and numbers of all
salesmen who had more than one customer. 3. List all salesmen and indicate those who have and
don’t have customers in their cities (Use UNION operation.) 4. Create a view that finds the
salesman who has the customer with the highest order of a day. 5. Demonstrate the DELETE
operation by removing salesman with id 1000. All his orders must also be deleted.

Solution:

Entity-Relationship Diagram

Table Creation

CREATE TABLE SALESMAN (SALESMAN_ID NUMBER (4), NAME VARCHAR2 (20), CITY
VARCHAR2 (20), COMMISSION VARCHAR2 (20), PRIMARY KEY (SALESMAN_ID));

CREATE TABLE CUSTOMER1 (CUSTOMER_ID NUMBER (4), CUST_NAME VARCHAR2


(20), CITY VARCHAR2 (20), GRADE NUMBER (3), PRIMARY KEY (CUSTOMER_ID),
SALESMAN_ID REFERENCES SALESMAN (SALESMAN_ID) ON DELETE SET NULL);

25
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
CREATE TABLE ORDERS (ORD_NO NUMBER (5), PURCHASE_AMT NUMBER (10, 2),
ORD_DATE DATE, PRIMARY KEY (ORD_NO), CUSTOMER_ID REFERENCES CUSTOMER1
(CUSTOMER_ID) ON DELETE CASCADE, SALESMAN_ID REFERENCES SALESMAN
(SALESMAN_ID) ON DELETE CASCADE);

Table Descriptions

DESC SALESMAN;

DESC CUSTOMER1;

DESC ORDERS;

Insertion of Values to Tables

INSERT INTO SALESMAN VALUES (1000, ‗JOHN„,„BANGALORE„,„25 %„);


26
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
INSERT INTO SALESMAN VALUES (2000, ‗RAVI„,„BANGALORE„,„20 %„);
INSERT INTO SALESMAN VALUES (3000, ‗KUMAR„,„MYSORE„,„15 %„);
INSERT INTO SALESMAN VALUES (4000, ‗SMITH„,„DELHI„,„30 %„);
INSERT INTO SALESMAN VALUES (5000, ‗HARSHA„,„HYDRABAD„,„15 %„);
INSERT INTO CUSTOMER1 VALUES (10, ‗PREETHI„,„BANGALORE„, 100, 1000);
INSERT INTO CUSTOMER1 VALUES (11, ‗VIVEK„,„MANGALORE„, 300, 1000);
INSERT INTO CUSTOMER1 VALUES (12, ‗BHASKAR„,„CHENNAI„, 400, 2000);
INSERT INTO CUSTOMER1 VALUES (13, ‗CHETHAN„,„BANGALORE„, 200, 2000);
INSERT INTO CUSTOMER1 VALUES (14, ‗MAMATHA„,„BANGALORE„, 400, 3000);
INSERT INTO ORDERS VALUES (50, 5000, ‗04-MAY-17„, 10, 1000);
INSERT INTO ORDERS VALUES (51, 450, ‗20-JAN-17„, 10, 2000);

INSERT INTO ORDERS VALUES (52, 1000, ‗24-FEB-17„, 13, 2000);


INSERT INTO ORDERS VALUES (53, 3500, ‗13-APR-17„, 14, 3000);
INSERT INTO ORDERS VALUES (54, 550, ‗09-MAR-17„, 12, 2000);

SELECT * FROM SALESMAN;

SELECT * FROM CUSTOMER1;

SELECT * FROM ORDERS;

27
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

Queries:

1. Count the customers with grades above Bangalore’s average.

SELECT GRADE, COUNT (DISTINCT CUSTOMER_ID) FROM CUSTOMER1 GROUP


BY GRADE HAVING GRADE > (SELECT AVG(GRADE) FROM CUSTOMER1 WHERE
CITY='BANGALORE');

2. Find the name and numbers of all salesmen who had more than one customer.

SELECT SALESMAN_ID, NAME FROM SALESMAN A WHERE 1 < (SELECT COUNT


(*) FROM CUSTOMER1 WHERE SALESMAN_ID=A.SALESMAN_ID);

3. List all salesmen and indicate those who have and don’t have customers in their cities (Use
UNION operation.)

SELECT SALESMAN.SALESMAN_ID, NAME, CUST_NAME, COMMISSION FROM


SALESMAN, CUSTOMER1 WHERE SALESMAN.CITY = CUSTOMER1.CITY UNION
SELECT SALESMAN_ID, NAME, 'NO MATCH', COMMISSION FROM SALESMAN
WHERE NOT CITY = ANY (SELECT CITY FROM CUSTOMER1) ORDER BY 2 DESC;

4. Create a view that finds the salesman who has the customer with the highest order of a day.

CREATE VIEW ELITSALESMAN AS SELECT B.ORD_DATE, A.SALESMAN_ID,


A.NAME FROM SALESMAN A, ORDERS BWHERE A.SALESMAN_ID =
B.SALESMAN_ID AND B.PURCHASE_AMT=(SELECT MAX (PURCHASE_AMT)
FROM ORDERS C WHERE C.ORD_DATE = B.ORD_DATE);

28
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

5.Demonstrate the DELETE operation by removing salesman with id 1000. All his orders must
also be deleted. Use ON DELETE CASCADE at the end of foreign key definitions while creating
child table orders and then execute the following: Use ON DELETE SET NULL at the end of
foreign key definitions while creating child table customers and then executes the following:

DELETE FROM SALESMAN WHERE SALESMAN_ID=1000;

29
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

The Sales table records information about product sales, including the quantity sold, sale
date, and total price for each sale. It serves as a transactional data source for analyzing sales
trends.

Query:
-- Create Sales table

CREATE TABLE Sales (


sale_id INT PRIMARY KEY,
product_id INT,
quantity_sold INT,
sale_date DATE,
total_price DECIMAL(10, 2)
);

-- Insert sample data into Sales table

INSERT INTO Sales (sale_id, product_id, quantity_sold, sale_date, total_price) VALUES


(1, 101, 5, '2024-01-01', 2500.00),
(2, 102, 3, '2024-01-02', 900.00),
(3, 103, 2, '2024-01-02', 60.00),
(4, 104, 4, '2024-01-03', 80.00),
(5, 105, 6, '2024-01-03', 90.00);

Output:

Sales Table

2. Products Table
30
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

The Products table contains details about products, including their names, categories, and
unit prices. It provides reference data for linking product information to sales transactions.

Query:
-- Create Products table

CREATE TABLE Products (


product_id INT PRIMARY KEY,
product_name VARCHAR(100),
category VARCHAR(50),
unit_price DECIMAL(10, 2)
);

-- Insert sample data into Products table

INSERT INTO Products (product_id, product_name, category, unit_price) VALUES


(101, 'Laptop', 'Electronics', 500.00),
(102, 'Smartphone', 'Electronics', 300.00),
(103, 'Headphones', 'Electronics', 30.00),
(104, 'Keyboard', 'Electronics', 20.00),
(105, 'Mouse', 'Electronics', 15.00);

Output:

Products Table

QUERIES

1. Retrieve all columns from the Sales table.


Query:
SELECT * FROM Sales;
Explanation:
31
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
This SQL query selects all columns from the Sales table, denoted by the asterisk (*)
wildcard. It retrieves every row and all associated columns from the Sales table.

2. Retrieve the product_name and unit_price from the Products table.


Query:
SELECT product_name, unit_price FROM Products;
Explanation:
This SQL query selects the product_name and unit_price columns from the Products table. It
retrieves every row but only the specified columns, which are product_name and unit_price.

3. Retrieve the sale_id and sale_date from the Sales table.


Query:
SELECT sale_id, sale_date FROM Sales;
Explanation:
This SQL query selects the sale_id and sale_date columns from the Sales table. It retrieves
every row but only the specified columns, which are sale_id and sale_date.

4. Filter the Sales table to show only sales with a total_price greater than $100.
Query:
SELECT * FROM Sales WHERE total_price > 100;
Explanation:
This SQL query selects all columns from the Sales table but only returns rows where the
total_price column is greater than 100. It filters out sales with a total_price less than or equal to
$100.

5. Filter the Products table to show only products in the 'Electronics' category.
Query:
SELECT * FROM Products WHERE category = 'Electronics';
Explanation:
This SQL query selects all columns from the Products table but only returns rows where the
category column equals 'Electronics'. It filters out products that do not belong to the
'Electronics' category.

6. Retrieve the sale_id and total_price from the Sales table for sales made on January 3,
2024.
Query:
SELECT sale_id, total_price
FROM Sales
WHERE sale_date = '2024-01-03';

32
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
7. Retrieve the product_id and product_name from the Products table for products with
a unit_price greater than $100.
Query:
SELECT product_id, product_name
FROM Products
WHERE unit_price > 100;
Explanation:
This SQL query selects the product_id and product_name columns from the Products table but
only returns rows where the unit_price is greater than $100. It filters out products with a
unit_price less than or equal to $100.

8. Calculate the total revenue generated from all sales in the Sales table.
Query:
SELECT SUM(total_price) AS total_revenue
FROM Sales;
Explanation:
This SQL query calculates the total revenue generated from all sales by summing up the
total_price column in the Sales table using the SUM() function.

9. Calculate the average unit_price of products in the Products table.


Query:
SELECT AVG(unit_price) AS average_unit_price
FROM Products;
Explanation:
This SQL query calculates the average unit_price of products by averaging the values in the
unit_price column in the Products table using the AVG() function.

10. Calculate the total quantity_sold from the Sales table.


Query:
SELECT SUM(quantity_sold) AS total_quantity_sold
FROM Sales;
Explanation:
This SQL query calculates the total quantity_sold by summing up the quantity_sold column in
the Sales table using the SUM() function.

11. Count Sales Per Day from the Sales table


Query:
SELECT sale_date, COUNT(*) AS sales_count
FROM Sales
GROUP BY sale_date
ORDER BY sale_date;
33
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

12. Retrieve product_name and unit_price from the Products table with the Highest Unit
Price
Query:
SELECT product_name, unit_price
FROM Products
ORDER BY unit_price DESC
LIMIT 1;
Explanation:
This query sorts the Products table by unit_price in descending order and retrieves the product
with the highest price using the LIMIT clause.

13. Retrieve the sale_id, product_id, and total_price from the Sales table for sales with a
quantity_sold greater than 4.
Query:
SELECT sale_id, product_id, total_price
FROM Sales
WHERE quantity_sold > 4;
Explanation:
This SQL query selects the sale_id, product_id, and total_price columns from the Sales table
but only returns rows where the quantity_sold is greater than 4.

14. Retrieve the product_name and unit_price from the Products table, ordering the
results by unit_price in descending order.
Query:
SELECT product_name, unit_price
FROM Products
ORDER BY unit_price DESC;
Explanation:
This SQL query selects the product_name and unit_price columns from the Products table and
orders the results by unit_price in descending order using the ORDER BY clause with
the DESC keyword.

15. Retrieve the total_price of all sales, rounding the values to two decimal places.
Query:
SELECT ROUND(SUM(total_price), 2) AS total_sales
FROM Sales;
Explanation:
This SQL query calculates the total sales revenu by summing up the total_price column in the
Sales table and rounds the result to two decimal places using the ROUND() function.

34
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM
16. Calculate the average total_price of sales in the Sales table.
Query:
SELECT AVG(total_price) AS average_total_price
FROM Sales;
Explanation:
This SQL query calculates the average total_price of sales by averaging the values in the
total_price column in the Sales table using the AVG() function.

17. Retrieve the sale_id and sale_date from the Sales table, formatting the sale_date as
'YYYY-MM-DD'.
Query:
SELECT sale_id, DATE_FORMAT(sale_date, '%Y-%m-%d') AS formatted_date
FROM Sales;

18. Calculate the total revenue generated from sales of products in the 'Electronics'
category.
Query:
SELECT SUM(Sales.total_price) AS total_revenue
FROM Sales
JOIN Products ON Sales.product_id = Products.product_id
WHERE Products.category = 'Electronics';
Explanation:
This SQL query calculates the total revenue generated from sales of products in the
'Electronics' category by joining the Sales table with the Products table on the product_id
column and filtering sales for products in the 'Electronics' category.

19. Retrieve the product_name and unit_price from the Products table, filtering the
unit_price to show only values between $20 and $600.
Query:
SELECT product_name, unit_price
FROM Products
WHERE unit_price BETWEEN 20 AND 600;
Explanation:
This SQL query selects the product_name and unit_price columns from the Products table but
only returns rows where the unit_price falls within the range of $20 and $600 using the
BETWEEN operator.

35
DEPARTMENT OF CSE 2023-2024
BCS403 DATABASE MANAGEMENT SYSTEM

20. Retrieve the product_name and category from the Products table, ordering the
results by category in ascending order.
Query:
SELECT product_name, category
FROM Products
ORDER BY category ASC;
Explanation:
This SQL query selects the product_name and category columns from the Products table and
orders the results by category in ascending order using the ORDER BY clause with the ASC
keyword.

36
DEPARTMENT OF CSE 2023-2024

You might also like