Dbms Lab Manual
Dbms Lab Manual
LABORATORY MANUAL
SUBJECT: DATABASE MANAGEMENT SYSTEM
SEMESTER: IV
SCHEME: 2022
Institute Mission
Department Vision
To impart technical education in the field of Artificial intelligence and
machine learning of topnotch quality with a high level of professional
competence, social obligation, and global cognizance among the students.
Department Mission
To impart technical education that is up to date, relevant and makes
students to compete at global level
Fostering an ambiance where students can adopt the suitable moral,
intellectual, emotional, and physical attributes to shine as the leaders
of tomorrow’s society.
To strive to meet ever higher educational standard.
Program Outcomes (PO’s)
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
3. Design/development of solutions: Design solutions for complex engineering problems 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.
methods including design of experiments, analysis and interpretation of data, and synthesis of the
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
6. 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
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
9. Individual and team work: Function effectively as an individual, and as a member or leader in
engineering community and with society at large, such as, being able to comprehend and write
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PEO1: Graduates will be able to hone their problem-solving abilities and capacity to offer solutions to
PEO2: Able to design and develop AI based solutions to real-world problems in a business, research,
or social environment.
PEO3: Graduates shall acquire and inculcate corporate culture, core attributes, and leadership qualities
PSO1: Ability to design and develop artificial intelligent based solutions by applying optimal
PSO2: Ability to apply suitable AI tools and techniques to offer solutions in the various domains of
engineering.
TABLE OF CONTENTS
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 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.
2 Create a table called Employee that contain attributes EMPNO, ENAME, JOB, MGR, SAL &
executethe 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.
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 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.
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 & extract 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
thenewly 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.
● Analyze 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
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 AssessmentTests (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 CIEmarks 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 theorycomponent 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
for50 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.
SI NO Particulars Page
No
1. INTRODUCTION TO DATABASE 1
2. EXPERITMENT 1 23
3. EXPERITMENT 2 27
4. EXPERITMENT 3 30
5. EXPERITMENT 4 32
6. EXPERITMENT 5 36
7. EXPERITMENT 6 38
8. EXPERITMENT 7 42
9. VIVA QUESTIONS
51
DATABASE MANAGEMENT SYSTEM BCS403
DBMS LABORATORY
Hardware requirements: Any CPU with Pentium Processor or similar,256 MB RAM or more,
1 GB Hard Disk or more.
THEORY
MySQL is a popular open-source relational database management system (RDBMS) choice for
web-based applications. Developers, database administrators use MySQL to build and manage
next-generation web- and cloud-based applications. With most open-source RDBMS options,
MySQL is available in several different editions and runs on Windows, OS X, Solaris, FreeBSD
and other variants of Linux and Unix
MySQL Workbench
MySQL Workbench is a unified visual tool for database architects, developers, and DBAs.
MySQL Workbench provides data modeling, SQL development, and comprehensive
administration tools for server configuration, user administration, backup, and much more.
MySQL Workbench is available on Windows, Linux and Mac OS X.
Design
MySQL Workbench enables a DBA, developer, or data architect to visually design, model,
generate, and manage databases. It includes everything a data modeler needs for creating
complex ER models, forward and reverse engineering, and also delivers key features for
performing difficult change management and documentation tasks that normally require much
time and effort.
1
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Develop
MySQL Workbench delivers visual tools for creating, executing, and optimizing SQL queries.
The SQL Editor provides color syntax highlighting, auto-complete, reuse of SQL snippets, and
execution history of SQL. The Database Connections Panel enables developers to easily manage
standard database connections, including MySQL Fabric. The Object Browser provides instant
access to database schema and objects.
Database Migration
MySQL Workbench now provides a complete, easy to use solution for migrating Microsoft
SQL Server, Microsoft Access, Sybase ASE, PostgreSQL, and other RDBMS tables, objects
and data to MySQL. Developers and DBAs can quickly and easily convert existing applications
to run on MySQL both on Windows and other platforms. Migration also supports migrating
from earlier versions of MySQL to the latest releases
Administer
MySQL Workbench provides a visual console to easily administer MySQL environments and
gain better visibility into databases. Developers and DBAs can use the visual tools for
configuring servers, administering users, performing backup and recovery, inspecting audit
data, and viewing database health.
2
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Design and Develop SQL DDL statements which demonstrate the use of SQL objects such
as
Introduction to SQL:
SQL stands for Structured Query Language SQLlets you access and manipulate databases
SQL is an ANSI (American National Standards Institute) standard
Commands of SQL are grouped into four languages.
1>DDL
DDL is abbreviation of Data Definition Language. It is used to create and modify the structure
of database objects in database.
2>DML
3>DCL
DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and
referential integrity as well it is used to control access to database by securing it.
Examples: GRANT, REVOKE statements
4>TCL
1.Data definition Language (DDL) is used to create, rename, alter, modify, drop, replace, and
delete tables, Indexes, Views, and comment on database objects; and establish a default
database.
2.The DDL part of SQL permits database tables to be created or deleted. It also defines indexes
(keys), specify links between tables, and impose constraints between tables. The most important
DDL statements in SQL are:
Syntax
CREATE TABLE table name
(attr1_name attr1_datatype(size) attr1_constraint, attr2_name attr2_datatype(size)
attr2_constraint,….);
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after
the table is created (with the ALTER TABLE statement).
We will focus on the following constraints:
NOT NULL
UNIQUE PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
Syntax
DROP TABLE table_name;
Syntax
To add a column in a table, use the following syntax:
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;
1. Index in SQL is created on existing tables to retrieve the rows quickly. When there are
thousands of records in a
table, retrieving information will take a long time.
2. Therefore, indexes are created on columns which are accessed frequently, so that
theinformation can be
retrieved quickly.
3. Indexes can be created on a single column or a group of columns. When a index is created,
it first sorts the
data and then it assigns a ROWID for each row.
Syntax
CREATE INDEX index_name
ON table_name (column_name1, column_name2...);
index_name is the name of the INDEX.
table_name is the name of the table to which the indexed column belongs.
column_name1, column_name2. is the list of columns which make up the INDEX.
1. Use the CREATE SYNONYM statement to create a synonym, which is an alternative name
5
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
for a table, view, sequence, procedure, stored function, package, materialized view.
2. Synonyms provide both data independence and location transparency. Synonyms permit
applications to function without modification regardless of which user owns the table or view and regardless
of which database holds the table or view.
3. You can refer to synonyms in the following DML statements: SELECT, INSERT, UPDATE,
DELETE
Syntax - Create synonym synonym-name for object-name;
Example-Create synonym synonym_name for table_name
DML command
Data Manipulation Language (DML) statements are used for managing data in database.
DMLcommands are not auto-committed. It means changes made by DML command are not
permanent to database, it can be rolled back.
1) INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
INSERT into table-name values(data1,data2,..)
Lets see an example,
Consider a table Student with following fields.S_id S_Name age
INSERT into Student values(101,'Adam',15);
The above command will insert a record into Student table.
S_id S_Name age 101 Adam 15
2) UPDATE command
Update command is used to update a row of a table. Following is its general syntax,
UPDATE table-name set column-name = value where condition;
Lets see an example,
update Student set age=18 where s_id=102;
Example to Update multiple columns
UPDATE Student set s_name='Abhi',age=17 where s_id=103;
3) Delete command
Delete command is used to delete data from a table. Delete command can also be used with condition to
delete a particular row.
Following is its general syntax,
DELETE from table-name;
Example to Delete all Records from a Table
DELETE from Student;
The above command will delete all the records from Student table.
Example to Delete a particular Record from a Table
Consider Student table
DELETE from Student where s_id=103;
SQL Functions
SQL provides many built-in functions to perform operations on data. These functions are useful
while performing mathematical calculations, string concatenations, sub-strings etc. SQL
functions are divided into two categories,
6
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
• Aggregate Functions
• Scalar Functions
Aggregate Functions
These functions return a single value after calculating from a group of values. Following are some
frequently used Aggregate functions.
1) AVG ()
Average returns average value after calculating from values in a numeric column.
Its general Syntax is,
SELECT AVG (column_name) from table_name
e.g. SELECT avg(salary) from Emp;
2) COUNT ()
Count returns the number of rows present in the table either based on some condition or without
condition. Its general Syntax is,
SELECT COUNT (column_name) from table-name;
Example using COUNT ()
Consider following Emp table
eid name age salary
401 Anu 22 9000
402 Shane 29 8000
SQL query to count employees, satisfying specified condition is,
SELECT COUNT (name) from Emp where salary = 8000;
3) FIRST ()
First function returns first value of a selected column
Syntax for FIRST function is,
SELECT FIRST (column_name) from table-name
SQL query
SELECT FIRST (salary) from Emp;
4) LAST ()
LAST return the return last value from selected column
Syntax of LAST function is,
SELECT LAST(column_name) from table-name
SQL query will be,
SELECT LAST(salary) from emp;
5) MAX()
MAX function returns maximum value from selected column of the table.
Syntax of MAX function is,
SELECT MAX(column_name) from table-name
SQL query to find Maximum salary is,
SELECT MAX(salary) from emp;
6) MIN()
MIN function returns minimum value from a selected column of the table.
Syntax for MIN function is,
7
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
7) SUM()
SUM function returns total sum of a selected columns numeric values.
Syntax for SUM is,
SELECT SUM(column_name) from table-name
SQL query to find sum of salaries will be,
SELECT SUM(salary) from emp;
Scalar Functions
Scalar functions return a single value from an input value. Following are soe frequently used
Scalar Functions.
1) UCASE()
UCASE function is used to convert value of string column to Uppercase character.
Syntax of UCASE,
SELECT UCASE(column_name) from table-name
Example of UCASE()
SQL query for using UCASE is,
SELECT UCASE(name) from emp;
2) LCASE()
LCASE function is used to convert value of string column to Lowercase character.
Syntax for LCASE is:
SELECT LCASE(column_name) from table-name
3) MID()
MID function is used to extract substrings from column values of string type in a table.
Syntax for MID function is:
SELECT MID(column_name, start, length) from table-name
4) ROUND()
ROUND function is used to round a numeric field to number of nearest integer. It is used on Decimal
point values.
Syntax of Round function is,
SELECT ROUND(column_name, decimals) from table-name
Operators:
AND and OR operators are used with Where clause to make more precise conditions for
fetching data from database by combining more than one condition together.
1) AND operator
AND operator is used to set multiple conditions with Where clause.
Example of AND
SELECT * from Emp WHERE salary < 10000 AND age > 25
2) OR operator
OR operator is also used to combine multiple conditions with Where clause. The only difference
between AND and OR is their behavior. When we use AND to combine two or morethan two
conditions, records satisfying all the condition will be in the result. But in case of OR,at least
one condition from the conditions specified must be satisfied by any record to be in the result.
8
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Example of OR
SELECT * from Emp WHERE salary > 10000 OR age
> 25 Set Operation in SQL
SQL supports few Set operations to be performed on table data. These are used to get
meaningful results from data, under different special conditions.
3) Union
UNION is used to combine the results of two or more Select statements. However, it will
eliminate duplicate rows from its result set. In case of union, number of columns and
datatype must be same in both the tables.
Example of UNION
select * from First
UNION
select * from second
4) Union All
This operation is similar to Union. But it also shows the duplicate rows.Union All query
will be like,
select * from
First UNION
ALL
select * from second
5) Intersect
Intersect operation is used to combine two SELECT statements, but it only returns the
records which are common from both SELECT statements. In case of Intersect the number
of columns and datatype must be same. MySQL does not support INTERSECT operator.
Intersect query will be,
select * from First
INTERSECT
select * from second
6) Minus
Minus operation combines result of two Select statements and return only those result
which belongs to first set of result. MySQL does not support INTERSECT operator.
Minus query will be,
select * from First
MINUS
select * from second
9
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
SQL triggers only can provide an extended validation and they cannot replace all the
validations. Some simple validations have to be done in the application layer. For example, you
can validate user’s inputs in the client side by using JavaScript or on the server side using server-
side scripting languages such as JSP, PHP, ASP.NET, Perl.
SQL triggers are invoked and executed invisible from the client applications,
therefore, it is difficult to figure out what happens in the database layer.
SQL triggers may increase the overhead of the database server.
In MySQL, trigger can also be created. There are 6 type of triggers that can be made they are: -
1. After/Before insert
2. After/Before update
3.After/Before delete
10
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
CREATE TRIGGER
trigger_nametrigger_event
ON table_name
FOR EACH ROW
BEGIN ... END;
Here,
Trigger_name is the name of the trigger which must be put after CREATE TRIGGER statement.
The naming convention for trigger_name can be like [trigger time] _ [table name] _
[trigger event]. For example, before_student_update or after_student_insert can be a name of the
trigger.
Trigger time is the time of trigger activation and it can be BEFORE or AFTER. We must
have to specify the activation time while defining a trigger. We must to use BEFORE if we want
to process action prior to the change made on the table and AFTER if we want to process action
post to the change made on the table.
Trigger event can be INSERT, UPDATE or DELETE. This event causes the trigger to be
invoked. A trigger only can be invoked by one event. To define a trigger that is invoked by
multiple events, we have to define multiple triggers, one for each event.
Table_name is the name of the table. Actually, a trigger is always associated with a
specific table. Without a table, a trigger would not exist hence we have to specify the
tablename after the ‘ON’ keyword.
BEGIN…END is the block in which we will define the logic for the trigger.
11
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Syntax:
CREATE TRIGGER trigger_name
AFTER/BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
--variable declarations
--trigger code
END;
Parameter:
trigger_name: name of the trigger to be created.
AFTER UPDATE: It points the trigger update query is executed.
table_name: name of the table in which a trigger is created.
Syntax:
Parameter:
trigger_name: name of the trigger to be created.
AFTER/BEFORE DELETE: It points the trigger after/before delete query is executed.
table_name: name of the table in which a trigger is created.
AUDIT TRACKING
EXAMPLES OF TRIGGERS FOR AUDIT PURPOSE
CREATE TABLE
Employee_Details(Emp_ID int primary key , Emp_Name
varchar(55), Emp_Sal decimal (10,2));
CREATE TABLE
Employee_Details_Audit(Emp_ID int, Emp_Name varchar (55), Emp_Sal decimal(10,2),
Action varchar(55)) ;
12
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Above we have two scripts for creating two table Employee_Details and
Employee_Details_Audit.Both tables have same no of column names,same column name and
same date type. In second table, Employee_Details_Audit keeps track of what kind of
operations are performed on table Employee_Details and any insert, update and delete
operation value are stored in Employee_Details_Audit
Below we have written three types of trigger meant for auditing purpose. What ever operations
performed on table Employee_Details gets automatically reflected in Employee_Details_Audit.
For example, we perform any insert, update or delete operations on Employee_Details, its get
automatically get reflected in Employee_Details_Audit table becausewe have written triggers
on Employee_Details table.
13
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
TRIGGER EXAMPLE 1
EXAMPLE OF CREATING AFTER INSERT TRIGGER FOR AUDIT PURPOSE
CREATE TRIGGER
TriggerAfterInsert AFTER
INSERT ON Employee_Details
FOR EACH ROW
insert into Employee_Details_Audit
values(new.Emp_ID,new.Emp_Name,new.Emp_Sal,'INSERT')
14
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
TRIGGER EXAMPLE 2
15
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
A procedure can return one or more than one value through parameters or may not return
at all. The procedure can be used in SQL queries.
Creating aprocedureSyntax
CREATE PROCEDURE
procedure_name(parameter datatype,
16
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Parameter datatype)
BEGIN
Declaration_section Executable_section
END;
Parameter
procedure_name: name of the stored procedure.
Parameter: number of parameters. It can be one or more
than one.declaration_section: all variables are declared.
executable_section: code is written here.
A variable is a named data object whose value can change during the stored procedure
execution. We typically use the variables in stored procedures to hold the immediate results.
These variables are local to the stored procedure. You must declare a variable before using
it.
DELIMITER //
CREATE PROCEDURE
sp_name(p_1 INT)
BEGIN
...code goes
here...END
// DELIMITER;
Replace procedure_name with sp_procedure_name whatever name you'd like to use for the
stored procedure. The parentheses are required — they enclose any parameters. If no parameters
are required, the parentheses can be empty.
The main body of the stored procedure goes in between the BEGIN and END keywords.
These keywords are used for writing compound statements. A compound statement can
contain multiple statements, and these can be nested if required. Therefore, you can nest
BEGIN and END blocks.
In most cases, you will also need to surround the CREATE PROCEDURE statement with
DELIMITER commands and change END; to END //. Like this:
17
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
In this case, the delimiter is changed from the semicolon (;) to double-slashes (//) We need to
change delimiter from; to //. Because we want to pass the stored procedure to the server as a
whole rather than letting MySQL tool interpret each statement at a time
Following the END keyword, we use the delimiter // to indicate the end of the stored procedure.
The last command (DELIMITER;) changes the delimiter back to the semicolon(;).
create table employee (employee_id int primary key, Name varchar (50),
Designation varchar (50), Salary decimal (10,2))
18
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Example
We are going to develop a simple stored procedure named SP_getEmployee to help you get
familiar with the syntax. The SP_getEmployee() stored procedure selects all employee
information from the employee table.:
DELIMITER $$
DROP PROCEDURE IF EXISTS
SP_getEmployee $$CREATE PROCEDURE
SP_getEmployee()
BEGIN
SELECT * FROM
employee;END$$
Execute the stored procedure above as follows:
call SP_getEmployee();
19
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Concept of Normalization
A large database defined as a single relation may result in data duplication. This repetition of
data may result in:
Making relations very large.
It isn't easy to maintain and update data as it would involve searching many records in relation.
Wastage and poor utilization of disk space and resources.
The likelihood of errors and inconsistencies increases.
So to handle these problems, we should analyze and decompose the relations with redundant data
into smaller, simpler, and well-structured relations that are satisfy desirable properties.
Normalization is a process of decomposing the relations into relations with fewer attributes.
What is Normalization?
Normalization is the process of organizing the data in the database.
Normalization is used to minimize the redundancy from a relation or set of relations. It is also
used to eliminate undesirable characteristics like Insertion, Update, and Deletion Anomalies.
Normalization divides the larger table into smaller and links them using relationships.
The normal form is used to reduce redundancy from the database table.
Advantages of Normalization
Normalization helps to minimize data redundancy.
Greater overall database organization.
Data consistency within the database.
Much more flexible database design.
Enforces the concept of relational integrity.
20
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Disadvantages of Normalization
You cannot start building the database before knowing what the user needs.
It is very time-consuming and difficult to normalize relations of a higher degree.
Careless decomposition may lead to a bad database design, leading to serious problems
Concepts of MongoDB
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The
term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like
relational database structure but provides an altogether different mechanism for storage and retrieval
of data. This format of storage is called BSON (similar to JSON format).
SQL databases store data in tabular format. This data is stored in a predefined data model which is
not very much flexible for today’s real-world highly growing applications. Modern applications
are more networked, social and interactive than ever. Applications are storing more and more
data and are accessing it at higher rates.
Relational Database Management System(RDBMS) is not the correct choice when it comes to
handling big data by the virtue of their design since they are not horizontally scalable. If the
database runs on a single server, then it will reach a scaling limit. NoSQL databases are more
scalable and provide superior performance. MongoDB is such a NoSQL database that scales by
adding more and more servers and increases productivity with its flexible document model.
RDBMS vs MongoDB:
RDBMS has a typical schema design that shows number of tables and the relationship between
these tables whereas MongoDB is document-oriented. There is no concept of schema or
relationship.
Complex transactions are not supported in MongoDB because complex join operations are not
available.
MongoDB allows a highly flexible and scalable document structure. For example, one data
document of a collection in MongoDB can have two fields whereas the other document in the same
collection can have four.
MongoDB is faster as compared to RDBMS due to efficient indexing and storage techniques.
There are a few terms that are related in both databases. What’s called Table in RDBMS is called
a Collection in MongoDB. Similarly, a Row is called a Document and a Column is called a Field.
MongoDB provides a default ‘_id’ (if not provided explicitly) which is a 12-byte hexadecimal
number that assures the uniqueness of every document. It is similar to the Primary key in RDBMS.
Features of MongoDB:
Document Oriented: MongoDB stores the main subject in the minimal number of documents
and not by breaking it up into multiple relational structures like RDBMS. For example, it stores all
the information of a computer in a single document called Computer and not in distinct relational
structures like CPU, RAM, Hard disk, etc.
21
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Indexing: Without indexing, a database would have to scan every document of a collection to
select those that match the query which would be inefficient. So, for efficient searching Indexing is
a must and MongoDB uses it to process huge volumes of data in very less time.
Scalability: MongoDB scales horizontally using sharding (partitioning data across various
servers). Data is partitioned into data chunks using the shard key, and these data chunks are evenly
distributed across shards that reside across many physical servers. Also, new machines can be added
to a running database.
Replication and High Availability: MongoDB increases the data availability with multiple
copies of data on different servers. By providing redundancy, it protects the database from hardware
failures. If one server goes down, the data can be retrieved easily from other active servers which
also had the data stored on them.
Aggregation: Aggregation operations process data records and return the computed results. It is
similar to the GROUPBY clause in SQL. A few aggregation expressions are sum, avg, min, max,
etc
Big Data: If you have huge amount of data to be stored in tables, think of MongoDB before
RDBMS databases. MongoDB has built-in solution for partitioning and sharing your database.
Unstable Schema: Adding a new column in RDBMS is hard whereas MongoDB is schema-less.
Adding a new field does not affect old documents and will be very easy.
Distributed data Since multiple copies of data are stored across different servers, recovery of
data is instant and safe even if there is a hardware failure.
22
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Lab Experiments:
Program 1: Create a table called Employee & execute the following.
Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION)
23
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
-- START A
TRANSACTIONSTART
TRANSACTION;
INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION)
VALUES (1, 'Ajay Kumar', 'Manager', 2, 5000.00, 1000.00);
INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION)
VALUES (2, 'Amith Kumar', 'HRManager', 4, 7000.00, 3000.00);
INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL,
COMMISSION)VALUES (3, 'Aman Kumar', 'Tester', 8, 3000.00, 2000.00);
COMMIT;
24
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
-- START ANOTHER
TRANSACTIONSTART
TRANSACTION;
INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION)
VALUES (4, 'Pradeep Kumar', 'FinanceManager', 5, 8000.00,4000.00);
UPDATE Employee SET ENAME='Sanjay Kumar' where EMPNO=2;
DELETE FROM Employee where ENAME = 'Ajay umar';
-- ROLLBACK 2 INSERTS AND 1 DELETE
OPERATIONS ROLLBACK;
3. Add primary key constraint and not null constraint to the employee table.
25
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
4. Insert null values to the employee table and verify the result.
INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION)
VALUES (5, 'Hemath', NULL,NULL, NULL, null);
26
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Program 2
Create a table called Employee that contain attributes EMPNO, ENAME,JOB, MGR,SAL &
execute the following.
Assuming that you want to set a domain for the COMMISSION which typically means defining a
specific range or type, standard doesn't directly support the "DOMAIN" keyword outside of Postgre.
However, you can ensure only positive values are entered by using a CHECK constraint:
INSERT INTO Employee (EMPNO, ENAME, JOB, MGR, SAL, COMMISSION) VALUES
(101, 'John Doe', 'Manager', NULL, 50000.00, 1500.00),
(102, 'Jane Smith', 'Developer', 101, 45000.00, 1000.00),
(103, 'Eric Johnson', 'Analyst', 101, 40000.00, 800.00),
(104, 'Mary Jane', 'Designer', 103, 35000.00, 500.00),
(105, 'Alice Brown', 'Tester', 104, 30000.00, 300.00);
27
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
To update the job title for an employee, you would use an UPDATE statement. For instance, if you
wanted to change the job title of all testers to 'Quality Analyst':
UPDATE Employee
SET JOB = 'Quality Analyst'
WHERE EMPNO = ‘105’;
28
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
This will remove the record for the employee with EMPNO 105 from the Employee table.
29
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Lab Program 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.
30
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
31
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Insertion Commands
INSERT INTO Employee (E_id, E_name, Age, Salary) VALUES
(1, 'John', 30, 50000.00),
(2, 'Jane', 35, 60000.00),
(3, 'David', 40, 70000.00),
(4, 'Emily', 25, 45000.00),
(5, 'Michael', 45, 80000.00);
______________________________________________________________________________________________________________________________________________________________________________________________________
Lab Program 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)
32
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
DELIMITER //
CREATE TRIGGER after_insert_salary_difference
AFTER INSERT ON CUSTOMERS
FOR EACH ROW
BEGIN
SET @my_sal_diff = CONCAT('salary inserted is ', NEW.SALARY);
END;//
DELIMITER ;
33
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
DELIMITER //
CREATE TRIGGER after_update_salary_difference
AFTER UPDATE ON CUSTOMERS
FOR EACH ROW
BEGIN
DECLARE old_salary DECIMAL(10, 2);
DECLARE new_salary DECIMAL(10, 2);
SET old_salary = OLD.SALARY;
SET new_salary = NEW.SALARY;
SET @my_sal_diff = CONCAT('salary difference after update is ', NEW.SALARY -
OLD.SALARY);
END;//
DELIMITER ;
OUTPUT:
INSERT INTO CUSTOMERS VALUES (6, 'amit kumar', 38,'bijapur', 90000.00)
UPDATE CUSTOMERS SET SALARY=95000 WHERE ID=6
SELECT @my_sal_diff AS salary_differnce
34
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
-- DELETE TRIGGER
DELIMITER //
CREATE TRIGGER after_delete_salary_difference
AFTER DELETE ON CUSTOMERS
FOR EACH ROW
BEGIN
SET @my_sal_diff = CONCAT('salary deleted is ', OLD.SALARY);
END;//
DELIMITER ;
35
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Lab Program 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)
36
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
DELIMITER $$
CREATE PROCEDURE gettable ( INOUT
Tableontents varchar(4000))
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE content varchar(100) DEFAULT "";
#Cursor declaration
DEClARE curName
CURSOR FOR
SELECT concat(E_id ,' , ' , E_name,Age ,' , ' , Salary) FROM Employee order by E_id desc;
#declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
#Open cursor
OPEN curName;
#fetch records
getName: LOOP
FETCH curName INTO content;
IF finished = 1 THEN LEAVE getName;
END IF;
SET Tableontents = CONCAT(content,";",Tableontents);
END LOOP getName;
CLOSE curName;
END$$
DELIMITER;
SET @Tableontents = "";
CALL gettable(@Tableontents);
SELECT @Tableontents;
Output
1, Samarth30, 50000.00;
2, Ramesh Kumar25, 45000.00;
3, Seema Banu35, 62000.00;
4, Dennis Anil28, 52000.00;
5, Rehman Khan32, 58000.00;'
37
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Lab Program 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.
Below is an example of a PL/SQL block of code that uses a parameterized cursor to merge data from
the N_RollCall table into the O_RollCall table, skipping records that already exist in the second table.
Table Schema
38
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
39
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
DELIMITER //
CREATE PROCEDURE merge_rollcall_data()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE n_id INT;
DECLARE n_name VARCHAR (255);
DECLARE n_birth_date DATE;
-- Declare cursor for N_RollCall table
DECLARE n_cursor CURSOR FOR
SELECT student_id, student_name, birth_date FROM N_RollCall;
-- Declare handler for cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET done = TRUE;
-- Open the cursor
OPEN n_cursor;
-- Start looping through cursor results
cursor_loop: 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 done THEN
LEAVE cursor_loop;
END IF;
-- Check if the data already exists in O_RollCallIF NOT EXISTS
40
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
CALL merge_rollcall_data();
SELECT * FROM O_RollCall;
This PL/SQL block iterates through each record in the N_RollCall table, checks if the record exists
in the O_RollCall table based on the ID, and inserts it into O_RollCall if it doesn't already exist.
41
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Lab Program 7
Install an Open Source NoSQL Data base MangoDB & perform basic CRUD(Create, Read,
Update & Delete) operations. Execute MangoDB basic Queries using CRUD operations.
let's go through the steps to install MongoDB and perform basic CRUD operations.
1. Install MongoDB
Ubuntu
bash
sudo apt update
sudo apt install -y mongodb
CentOS/RHEL
bash
sudo yum install -y mongodb-org
macOS
You can use Homebrew:
bash
brew tap mongodb/brew
brew install mongodb-community
Ubuntu
bash
sudo systemctl start mongodb
CentOS/RHEL
bash
sudo systemctl start mongod
42
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
macOS
bash
brew services start mongodb-community
3. Connect to MongoDB
bash
mongo
mongosh
use bookDB
switched to db bookDB
43
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
INSERT operations
a. Insert 5 Documents into the ProgrammingBooks Collection :
Now, insert 5 documents representing programming books into the ProgrammingBooks collection
using the insertMany () method:
44
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Use the insertOne() method to insert a new document into the ProgrammingBooks collection:
db.ProgrammingBooks.insertOne({
title: "The Pragmatic Programmer: Your Journey to Mastery",
author: "David Thomas, Andrew Hunt",
category: "Software Development",
year: 1999})
db.ProgrammingBooks.find(). pretty ()
45
Dept. of CSE, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
46
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Update Operations
a. Update a Single Document
To update a specific book (e.g., change the author of a book):
db.ProgrammingBooks.updateOne(
{ title: "Clean Code: A Handbook of Agile Software Craftsmanship" },
{ $set: { author: "Robert C. Martin (Uncle Bob)" } }
)
47
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
48
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Delete Operations
49
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
You can check whether the specified document is deleted by displaying the contents of the
collection.
You can check whether the specified documents were deleted by displaying the contents of the
collection.
db.ProgrammingBooks.deleteMany({})
50
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
Viva Questions
1. What is SQL?
Structured Query Language
2. What is database?
A database is a logically coherent collection of data with some inherent meaning,
representing some aspect of real world and which is designed, built and populated with
data for a specific purpose.
3. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other
words, it is general-purpose software that provides the users with the processes of defining,
constructing and manipulating the database for various applications.
4. What is a Database system?
The database and DBMS software together is called as Database system.
5. What are Advantages of DBMS?
Redundancy is controlled.
Unauthorized access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
6. What are Disadvantages in File Processing System?
Data redundancy &inconsistency.
Difficult in accessing data.
Data isolation.
Data integrity.
Concurrent access is not possible.
Security Problems.
7. Define the "integrity rules"
There are two Integrity rules.
Entity Integrity: States that “Primary key cannot have NULL value”
Referential Integrity: States that “Foreign Key can be either a NULL value or should be
Primary Key value of other relation.
51
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
data model.
52
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
20. What are partial, alternate, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same
owner entity. It is sometime called as Discriminator.
Alternate Key:
All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key:
If no obvious key, either standalone or compound is available, then the last resort is to simply
create a key, by assigning a unique number to each record or occurrence. Then this is known
as developing an artificial key.
Compound Key:
If no single data element uniquely identifies occurrences within a construct, then combining
multiple elements to create a unique identifier for the construct is known as creating a
compound key.
Natural Key:
When one of the data elements stored within a construct is utilized as the primary key, then it is
called the natural key.
21. What is meant by query optimization?
The phase that identifies an efficient execution plan for evaluating a query that has the
least estimated cost is referred to as query optimization.
22. 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.
53
DEPT. OF CSE-AI & ML, ATMECE, MYSURU
DATABASE MANAGEMENT SYSTEM BCS403
company was shifted to a freeware deployment model in 2009, providing sales assistance and
other services.
Generally, we use MongoDB as the main data store for the operational requirements with live
needs. Generally, MongoDB is suitable for 80% of the applications which we develop today.
MongoDB is simple to operate and extent in ways that are tough if they are not possible with the
relational databases.
MongoDB stands out in various use cases where the relational databases are not suitable, like
applications with semi-structured, structured, along with the big scalability needs or the multi-
datacenter deployments.
MongoDB cannot be suitable for some applications. For instance, applications that needcomplex
transactions and scan-based applications that access huge subsets of the data largely cannot be
suitable for MongoDB.
Some general uses of MongoDB comprise product catalogs, mobile apps, content management,
real-time personalization, and applications providing individual viewsthroughout several systems.
54
DEPT. OF CSE-AI & ML, ATMECE, MYSURU