Professional Documents
Culture Documents
Laboratory Manual
School of Computing
Name of the School:
Sciences and Engineering
Name of the Department: Computer Science and
Engineering
Name of the Programme: BTech CSE
Class: CSE
Database Management
Course/ Course Code:
System Lab 17YCS412
COVER PAGE
17YCS412-Database Management Systems Laboratory
Guidelines
Laboratory rules
1. Attendance is required for all lab classes. Students who do not attend lab will not
receive credit.
2. Ensure that you are aware of the test and its procedure before each lab class. You will
NOT be allowed to attend the class if you a renort unprepared!
3. Personal safety is top priority. Do not use equipment that is not assigned to you.
5. The surroundings near the equipment must be cleaned before leaving each lab class.
6. Ensure that readings are checked and marked by your TA for each lab period.
Laboratory report
NameofStudent ……………………………………
AcademicYear ……………………………………
Programme ……………………………………
Class/Div/RollNo. ……………………………………
PRNNo. ……………………………………
17YCS412-Database Management Systems Laboratory
CERTIFICTAE
of class…...........................has satisfactorily/unsatisfactorily
completed the Term Work of Course ……………………………….
in this School during academic year ………………….
Table of Contents
Sr. Page
Title of Experiment Date Remark Sign
No. No
1. Study of Open Source Databases: MySQL/
MongoDB/CouchDB etc. 2
Theory:
What is Database?
A database is a separate application that stores a collection of data.Each database has one or more
distinct APIs for creating, accessing, managing, searching and replicating the data it holds.
So nowadays, we use relational database management systems (RDBMS) to store and manage huge
Volume of data. This is called relational database because all the data is stored into different tables
and Relations are established using primary keys or other keys known as foreign keys.
What is DBMS?
A software system that enables users to define, create, maintain, and control access to the database.
The DBMS is the software that interacts with the users’ application programs and the database.
Typically, a DBMS provides the following facilities:
It allows users to define the database, usually through a Data Definition Language (DDL).
The DDL allows users to specify the data types and structures and the constraints on the data
to be stored in the database.
It allows users to insert, update, delete, and retrieve data from the database, usually through a
Data Manipulation Language(DML). The most common query language is the Structured
Query Language (SQL, pronounced ‘S-Q-L’, or sometimes ‘See-Quel’), which is now both
the formal and de facto standard language for relational DBMSs.
Column: One column(data element) contains data of one and the same kind, for example the
Column post code.
Row: A row(=tuple, entry or record) is a group of related data, for example the data of one
subscription.
Redundancy: Storing data twice, redundantly to make the system faster.
Primary Key: A primary key is unique. A key value cannot occur twice in one table.
With a key, you can find at most one row.
Foreign Key: A foreign key is the linking pin between two tables.
Compound Key: A compound key(composite key) is a key that consists of multiple columns,
Because one column is not sufficiently unique.
MySQL Database:
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed, and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons:
• MySQL is released under an open-source license. So you have nothing to pay to use it.
• MySQL is a very powerful program in its own right. It handle salarge subset of the functionality of
the most expensive and powerful database packages.
• MySQL uses a standard form of the well-known SQL data language.
• MySQLworksonmanyoperatingsystemsandwithmanylanguagesincludingPHP, PERL, C,C++,
JAVA,etc.
• MySQL works very quickly and works well even with large datasets. MySQL is very friendly to
PHP, the most appreciated language for web development.
• MySQL supports large databases, upto50millionrowsormoreinatable. The default file size limit for
atableis4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of
8million terabytes(TB).
• MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL
software to fit their own specific environments.
MongoDB Database:
MongoDB is a powerful, flexible, and scalable data store. It combines the ability to scale out with
many of the most useful features of relational databases, such as secondary indexes, range queries, and
sorting.
Features of MongoDB :
built-in support for MapReduce-style aggregation
geospatial indexes
o MongoDB is a document-oriented database, not a relational one.
o MongoDB is also schema-free
Indexing: MongoDB supports generic secondary indexes, allowing a variety of fast queries,
and provides unique, compound, and geospatial indexing capabilities as well.
Stored JavaScript: Instead of stored procedures, developers can store and use JavaScript
functions and values on the server side.
Aggregation : MongoDB supports MapReduce and other aggregation tools.
Fixed-size collections:Capped collections are fixed in size and are useful for certain types of
data, such as logs.
File storage : MongoDB supports an easy-to-use protocol for storing large files and file
metadata.
3
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Procedure:
Basic commands of MYSQL
mysql> CREATE DATABASE MyDatabase;
Query OK, 1 row affected (0.06 sec) //To create own databse
mysql> Show Databases;
+ +
| Database |
+ +
| info |
| mydatabase |
| mysql |
| test |
+ +
3 rows in set (0.00 sec)
4
YCA412/YCF412/YCI412-Database Management Systems Laboratory
5
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
Hence we learned use of open source databases.
6
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Title Design and Develop SQL DDL statements which demonstrate the use of SQL
objects.
Aim To demonstrate the use of SQL objects such as Table, View, Index, Sequence,
Synonym.
Objective Demonstrate use of DML clauses such as create, alter, delete clauses
Theory:
About MySQL
MySQL is open source database management software that helps users store, organize, and
retrieve data. It is a very powerful program with a lot of flexibility.
If you don't have MySQL installed on your droplet, you can quickly download it.
Once you have MySQL installed on your droplet, you can access the MySQL shell by typing
the following command into terminal:
mysql -u root -p
After entering the root MySQL password into the prompt, you will be able to start building
your MySQL database.
1. All MySQL commands end with a semicolon; if the phrase does not end with a semicolon, the
command will not execute.
2. Also, although it is not required, MySQL commands are usually written in uppercase and
databases, tables, usernames, or text are in lowercase to make them easier to distinguish.
However, the MySQL command line is not case sensitive.
MySQL organizes its information into databases; each one can hold tables with specific data.
7
YCA412/YCF412/YCI412-Database Management Systems Laboratory
SHOW DATABASES;
The first step is to create a new table within the larger database.
USE events;
In the same way that you could check the available databases, you can also see an overview
of the tables that the database contains.
SHOW tables;
Since this is a new database, MySQL has nothing to show, and you will get a message that
says, “Empty set”
Let’s imagine that we are planning a get together of friends. We can use MySQL to track the
details of the event.
Keep in mind throughout that, although the MySQL command line does not pay attention to
cases, the table and database names are case sensitive: potluck is not the same as POTLUCK
or Potluck.
mysql>DESCRIBE potluck;
A view can be created from many kinds of SELECT statements. It can refer to base tables or other
8
YCA412/YCF412/YCI412-Database Management Systems Laboratory
views. It can use joins, UNION, and subqueries. The SELECT need not even refer to any tables.
Procedure:
sudo apt-get install mysql-server
mysql> SHOW DATABASES;
+ +
| Database |
+ +
| information_schema |
| mysql |
| performance_schema |
| test |
+ +
4 rows in set (0.01 sec)
CREATE DATABASE database name;
Let’s take a look at how the table appears within the database using the "SHOW TABLES;"
command:
9
YCA412/YCF412/YCI412-Database Management Systems Laboratory
+ +
| potluck |
+ +
1 row in set (0.01 sec)
We can remind ourselves about the table’s organization with this command:
DESCRIBE potluck;
+ + + + + + +
| Field | Type | Null | Key | Default | Extra |
+ + + + + + +
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| food | varchar(30) | YES | | NULL | |
| confirmed | char(1) | YES | | NULL | |
| signup_date | date | YES | | NULL | |
+ + + + + + +
5 rows in set (0.01 sec)
The following example defines a view that selects two columns from another table as well as an
expression calculated from those columns:
+ + + +
+ + + +
| 3 | 50 | 150 |
+ + + +
10
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
11
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
Hence we learned to design and execute DDL statements in mysql.
12
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Title Design 10 SQL queries for suitable database application using SQL DML
statements.
Once you input that in, you will see the words:
Now that we have started our potluck list, we can address any possible changes. For example:
Sandy has confirmed that she is attending, so we are going to update that in the table.
UPDATE `potluck`
SET
`confirmed` = 'Y'
WHERE `potluck`.`name` ='Sandy';
You can also use this command to add information into specific cells, even if they are empty.
We are creating a handy chart, but it is missing some important information: our attendees’
emails.
This command puts the new column called "email" at the end of the table by default, and the
VARCHAR command limits it to 40 characters.
However, if you need to place that column in a specific spot in the table, we can add one more
phrase to the command.
Now the new “email” column goes after the column “name”.
Just as you can add a column, you can delete one as well:
If needed, you can also delete rows from the table with the following command:
For example, if Sandy suddenly realized that she will not be able to participate in the potluck
after all, we could quickly eliminate her details.
Notice that the id numbers associated with each person remain the same.
14
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
15
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
Hence we learned to design and execute DML statements in mysql.
16
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Title Design at least 10 SQL queries for suitable database application using SQL
DML statements: all types of Join, Sub-Query and View
Theory:
MySQL - LEFT JOIN and RIGHT JOIN, INNER JOIN and OUTER JOIN
In a database such as MySQL, data is divided into a series of tables which are then connected together
in SELECT commands to generate the output required. People often get confused between all the join
flavors. Let us consider an example to see how it works.
and also:
mysql>select*fromdemo_people; +------------+--------------+------+
17
YCA412/YCF412/YCI412-Database Management Systems Laboratory
+ + + +
+ + + +
Table 1
mysql>select*fromdemo_property; +------+------+--------------------- +
+ + + +
| 3 | 2 | The Willows |
| 3 | 3 | Tall Trees |
| 4 | 5 | Dun Roamin |
+ + + +
Table 2
If we do a regular JOIN (with none of the keywords INNER, OUTER, LEFT or RIGHT), then we get
all records that match in the appropriate way in the two tables, and records in both incoming tables
that do not match are not reported:
demo_people.pid = demo_property.pid;
If we do a LEFT JOIN, we get all records that match in the same way and IN ADDITION we get an
extra record for each unmatched record in the left table of the join - thus ensuring that every PERSON
gets a mention:
mysql> select name, phone, selling from demo_people left join demo_property
on demo_people.pid = demo_property.pid;
If we do a RIGHT JOIN, we get all the records that match and IN ADDITION we get an extra record
for each unmatched record in the right table of the join - in example, that means that each property
gets a mention even if we don't have seller details:
18
YCA412/YCF412/YCI412-Database Management Systems Laboratory
mysql> select name, phone, selling from demo_people right join demo_property
on demo_people.pid = demo_property.pid;
An INNER JOIN does a full join, just like the first example, and the word OUTER may be added
after the word LEFT or RIGHT in the last two examples - it's provided for ODBC compatibility
MySQL SubQuery
A MySQL subquery is a query that is nested inside another query such as SELECT, INSERT,
UPDATE or DELETE. A MySQL subquery is also can be nested inside another subquery. A MySQL
subquery is also called an inner query, while the query that contains the subquery is called an outer
query.
For example, the following query returns the customer who has the maximum payment.
MySQL View:
A database view is a virtual table or logical table which is defined as a SQL SELECT query with
joins. Because a database view is similar to a database table, which consists of rows and columns, so
you can query data against it.
19
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Mysql>create view X as
Where demo_people.pid=demo_people.pid;
Calling View:
SELECT * FROM X;
20
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
21
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
Hence we learned to design and execute DML join statements in mysql.
22
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Theory:
PL/SQL is a block structured language that enables developers to combine the power of SQL
with procedural statements.All the statements of a block are passed to oracle engine all at
once which increases processing speed and decreases the traffic.
Disadvantages of SQL:
SQL doesn’t provide the programmers with a technique of condition checking, looping and
branching.
SQL statements are passed to Oracle engine one at a time which increases traffic and
decreases speed.
SQL has no facility of error checking during manipulation of data.
Features of PL/SQL:
23
YCA412/YCF412/YCI412-Database Management Systems Laboratory
done.
Execute as a single statement. Execute as a whole block.
Mainly used to manipulate data. Mainly used to create an application.
It is an extension of SQL, so it can contain SQL
Cannot contain PL/SQL code in it.
inside it.
Typically, each block performs a logical action in the program. A block has the following
structure:
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
Declare section starts with DECLARE keyword in which variables, constants, records
as cursors can be declared which stores data temporarily. It basically consists
definition of PL/SQL identifiers. This part of the code is optional.
Execution section starts with BEGIN and ends with END keyword.This is a
mandatory section and here the program logic is written to perform any task like loops
and conditional statements. It supports all DML commands, DDL commands and
SQL*PLUS built-in functions as well.
Exception section starts with EXCEPTION keyword.This section is optional which
contains statements that are executed when a run-time error occurs. Any exceptions
can be handled in this section.
Procedure:
Create a table student
Mysql>CREATE TABLE student
(stud_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
24
YCA412/YCF412/YCI412-Database Management Systems Laboratory
START TRANSACTION;
SAVEPOINT all_or_none;
OPEN student_cursor;
Cursor_stud:LOOP
FETCH student_cursor
INTO pid,pm1,pm2,pm3;
If pm>=70 then
Select concat(‘distinction’,pm)as “rows”;
End if;
If pm>=60 then
Select concat(‘First’,pm)as “rows”;
End if;
If pm>=50 then
Select concat(‘second’,pm)as “rows”;
End if;
If pm<50 then
Select concat(‘Fail’,pm)as “rows”;
End if;
END LOOP;
CLOSE student_cursor;
END;
$$
26
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
27
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
Hence we learned to write and execute PL/SQL block to calculate the grade of minimum 10
students.
28
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Theory:
Cursors:
A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed
by it.
This temporary work area is used to store the data retrieved from the database, and
manipulate this data. A cursor can hold more than one row, but can process only one row at a
time. The set of rows the cursor holds is called the active set.
Asensitive: Asensitive cursor focus on genuine data. These cursors work faster than
the insensitive cursor. Asensitive cursor doesn’t need any duplicate copy of data. Any
alteration done in the data through dead end should effect the data contain in
asensitive cursors.
Read only: In read only data,there is only permission to read the data.And it doen’t
contain any permissions to updated the data or alter the data.
One directional: MySQL cursor moves only in one direction. Data fetching can be
done in only one direction,and cannot fetch data in opposite direction.
Declare a Cursor
Where,
29
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Open Statement
The syntax to open a cursor using the OPEN statement in MySQL is:
open <cursor_name>;
Where,
Fetch Statement
fetch<cursor_name>into<variable1>,<variable2>;
Where,
cursor_name - The name of the cursor that you wish to fetch rows.
variable_list - The list of variables, comma separated, that you wish to store the cursor result
set in.
Close Statement
close<cursor_name>;
Where,
cursor_name - The name of the cursor that you wish to close. '
Close Cursor
Close Cursor is used to close the Cursor upto some extent, when the open cursor is not
required. The keyword close in the cursor will discharge the present records to close and then
open the open cursor.
30
YCA412/YCF412/YCI412-Database Management Systems Laboratory
When working with MySQL cursor, you must also declare a NOT FOUND handler to handle
the situation when the cursor could not find any row. Because each time you call the FETCH
statement, the cursor attempts to read the next row in the result set. When the cursor reaches
the end of the result set, it will not be able to get the data, and a condition is raised. The
handler is used to handle this condition.
The syntax to set up a handler for the NOT FOUND condition for a cursor in MySQL is:
Where,
set_condition- The condition to set when the NOT FOUND condition is encountered by the cursor.
MySQL supports two types of cursors: Implicit Cursor and Explicit Cursor
1. Implicit cursors
When ever a client get a connection with the server by default Oracle server provides an
implicit work area to each client for it’s internal processing of MySQL statements. This work
area is dedicated to a specific client. This implicit work area is called as implicit cursor.
These are created by default when DML statements like, INSERT, UPDATE, and DELETE
statements are executed. They are also created when a SELECT statement that returns just
one row is executed.
A client can access the implicit cursor with the name MySQL. Cursors are used for rows
repetition returned by a query on a row-by-row process. SQL commands will function on all
the rows at one time in the program. Cursors can be created inside the triggers, functions and
stored procedures.
For Example: Consider the MySQL Block that uses implicit cursor attributes as shown
below:
2. Explicit cursors
They must be created when you are executing a SELECT statement that returns more than
one row. Even though the cursor stores multiple records, only one record can be processed at
a time, which is called as current row. When you fetch a row the current row position moves
to next row.
31
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Procedure:
Implicit cursor:
mysql> select * from CUSTOMERS;
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 3500.00 |
| 2 | Khilan | 25 | Delhi | 3000.00 |
| 3 | kaushik | 23 | Kota | 3500.00 |
| 4 | Chaitali | 25 | Mumbai | 8000.00 |
| 5 | Hardik | 27 | Bhopal | 10000.00 |
| 6 | Komal | 22 | MP | 6000.00 |
+ + + + + +
6 rows in set (0.00 sec)
mysql> delimiter $$
mysql> CREATE PROCEDURE CUR3()
-> BEGIN
-> DECLARE total_rows INT;
-> UPDATE CUSTOMERS SET SALARY = SALARY + 500;
->
-> END;
-> $$
Query OK, 0 rows affected (0.01 sec)
Explicit Cursor
Both implicit and explicit cursors have the same functionality, but they differ in the way they
are accessed.
mysql> CREATE PROCEDURE build_email_list1 (INOUT email_list varchar(4000))
32
YCA412/YCF412/YCI412-Database Management Systems Laboratory
-> BEGIN
-> DECLARE v_finished INTEGER DEFAULT 0;
-> DECLARE v_email varchar(100) DEFAULT "";
-> DEClARE email_cursor CURSOR FOR
-> SELECT email_list FROM employees;
-> DECLARE CONTINUE HANDLER
-> FOR NOT FOUND SET v_finished = 1;
-> OPEN email_cursor;
-> get_email: LOOP
-> FETCH email_cursor INTO v_email;
-> IF v_finished = 1 THEN
-> LEAVE get_email;
-> END IF;
-> SET email_list = CONCAT(v_email,";",email_list);
-> END LOOP get_email;
-> CLOSE email_cursor;
-> END
-> $$
Query OK, 0 rows affected (0.01 sec)
+
+
| @email_list |
+
+
33
YCA412/YCF412/YCI412-Database Management Systems Laboratory
| xyz@abc.com ;xyz@abc.com;xyz@abc.com;sxyz@abc.com;xyz@abc.com;xyz@abc.com|
+
+
1 row in set (0.00 sec)
34
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
35
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
36
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Theory:
A stored procedure or in simple a proc is a named PL/SQL block which performs one or
more specific task. This is similar to a procedure in other programming languages.
A procedure has a header and a body. The header consists of the name of the procedure and
the parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block.
A stored procedure is a segment of declarative SQL statements stored inside the database
catalog. A stored procedure can be invoked by triggers, other stored procedures, and
applications such as Java, Python, PHP, etc.
Typically stored procedures help increase the performance of the applications. Once
created, stored procedures are compiled and stored in the database. However, MySQL
implements the stored procedures slightly different. MySQL stored procedures are
compiled on demand. After compiling a stored procedure, MySQL puts it into a cache.
37
YCA412/YCF412/YCI412-Database Management Systems Laboratory
And MySQL maintains its own stored procedure cache for every single connection. If
an application uses a stored procedure multiple times in a single connection, the
compiled version is used, otherwise, the stored procedure works like a query.
Stored procedures help reduce the traffic between application and database server
because instead of sending multiple lengthy SQL statements, the application has to
send only name and parameters of the stored procedure.
Stored procedures are reusable and transparent to any applications. Stored procedures
expose the database interface to all applications so that developers don’t have to
develop functions that are already supported in stored procedures.
Stored procedures are secure. The database administrator can grant appropriate
permissions to applications that access stored procedures in the database without
giving any permissions on the underlying database tables.
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
IS - marks the beginning of the body of the procedure and is similar to DECLARE in
anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR
REPLACE together the procedure is created if no other procedure with the same name exists
or the existing procedure is replaced with the current code.
procedure_name;
1) IN type parameter: These types of parameters are used to send values to stored
procedures.
2) OUT type parameter: These types of parameters are used to get values from stored
procedures. This is similar to a return type in functions.
3) IN OUT parameter: These types of parameters are used to send values and get values
from stored procedures.
1) IN parameter:
It is the default mode. When you define an IN parameter in a stored procedure, the calling program has to
pass an argument to the stored procedure. In addition, the value of an IN parameter is protected. It means
that even the value of the IN parameter is changed inside the stored procedure, its original value is retained
after the stored procedure ends. In other words, the stored procedure only works on the copy of the IN
parameter.
+ + + + + +
+ + + + + +
39
YCA412/YCF412/YCI412-Database Management Systems Laboratory
| 6 | Komal | 22 | MP | 6500.00 |
+ + + + + +
IN parameter Example:
mysql> delimiter $$
-> begin
-> end;
-> $$
-> $$
+ + + + + +
+ + + + + +
+ + + + + +
40
YCA412/YCF412/YCI412-Database Management Systems Laboratory
2) OUT Parameter:
the value of an OUT parameter can be changed inside the stored procedure and its new value is
passed back to the calling program. Notice that the stored procedure cannot access the initial
value of the OUT parameter when it starts.
+ + + + + +
+ + + + + +
| 6 | Komal | 22 | MP | 6500.00 |
+ + + + + +
mysql> DELIMITER $$
41
YCA412/YCF412/YCI412-Database Management Systems Laboratory
-> BEGIN
-> END$$
+ +
| @total |
+ +
|2|
+ +
3) IN OUT Parameter:
The IN OUT parameter allows us to pass values into a procedure and get output values from
the procedure. This parameter is used if the value of the IN parameter can be changed in the
calling program.
By using IN OUT parameter we can pass values into a parameter and return a value to the
calling program using the same parameter. But this is possible only if the value passed to the
42
YCA412/YCF412/YCI412-Database Management Systems Laboratory
procedure and output value have a same datatype. This parameter is used if the value of the
parameter will be changed in the procedure.
mysql> DELIMITER $$
-> BEGIN
-> END$$
-> $$
-> $$
+ +
| @counter |
+ +
|1|
+ +
-> $$
43
YCA412/YCF412/YCI412-Database Management Systems Laboratory
-> $$
+ +
| @counter |
+ +
|2|
+ +
Stored Function
A stored function is a special kind stored program that returns a single value. You use stored
functions to encapsulate common formulas or business rules that are reusable among SQL
statements or stored programs.
Different from a stored procedure, you can use a stored function in SQL statements wherever
an expression is used. This helps improve the readability and maintainability of the
procedural code.
The following illustrates the simplest syntax for creating a new stored function:
RETURNS datatype
[NOT] DETERMINISTIC
statements
First, you specify the name of the stored function after CREATE FUNCTION clause.
44
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Second, you list all parameters of the stored function inside the parentheses. By default, all
parameters are IN parameters. You cannot specify IN , OUT or INOUT modifiers to the
parameters.
Third, you must specify the data type of the return value in the RETURNS statement. It can be
any valid MySQL data types.
Fourth, for the same input parameters, if the stored function returns the same result, it is
considered deterministic and otherwise the stored function is not deterministic. You have to
decide whether a stored function is deterministic or not. If you declare it incorrectly, the
stored function may produce an unexpected result, or the available optimization is not used
which degrades the performance.
Fifth, you write the code in the body of the stored function. It can be a single statement or a
compound statement. Inside the body section, you have to specify at least one RETURN
statement. The RETURN statement returns a value to the caller. Whenever the RETURN
statement is reached, the stored function’s execution is terminated immediately.
The following example is a function that returns the level of a customer based on credit limit.
We use the IF statement to decide the credit limit.
-> DETERMINISTIC
-> BEGIN
-> ELSEIF (cust_salary <= 10000 AND cust_salary >= 5000) THEN
45
YCA412/YCF412/YCI412-Database Management Systems Laboratory
->
-> END $$
+ + +
| NAME | CustomerLevel(SALARY) |
+ + +
| Chaitali | GOLD |
| Hardik | PLATINUM |
| kaushik | SILVER |
| Khilan | SILVER |
| Komal | GOLD |
| Ramesh | SILVER |
| vivek | SILVER |
| vivek | SILVER |
+ + +
46
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Result
47
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
Hence we learned to write a PL/SQL block to create Stored Procedure and Cursor.
48
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Theory:
SQL Trigger
A SQL trigger is a set of SQL statements stored in the database catalog. A SQL trigger is
executed or fired whenever an event associated with a table occurs e.g., insert, update or
delete.
A SQL trigger is a special type of stored procedure. It is special because it is not called
directly like a stored procedure. The main difference between a trigger and a stored procedure
is that a trigger is called automatically when a data modification event is made against a table
whereas a stored procedure must be called explicitly.
In MySQL, a trigger is a set of SQL statements that is invoked automatically when a change
is made to the data on the associated table. A trigger can be defined to be invoked either
before or after the data is changed by INSERT, UPDATE or DELETE statement. Before
MySQL version 5.7.2, you can to define maximum six triggers for each table.
49
YCA412/YCF412/YCI412-Database Management Systems Laboratory
MySQL triggers cover all features defined in the standard SQL. However, there are some
limitations that you should know before using them in your applications.
Use SHOW, LOAD DATA, LOAD TABLE, BACKUP DATABASE, RESTORE, FLUSH and
RETURN statements.
Use statements that commit or rollback implicitly or explicitly such as COMMIT ,
ROLLBACK , START TRANSACTION , LOCK/UNLOCK TABLES , ALTER ,
CREATE , DROP , RENAME , etc.
Use prepared statements such as PREPARE, EXECUTE, etc.
Use dynamic SQL statements.
In order to create a new trigger, you use the CREATE TRIGGER statement. The following
illustrates the syntax of the CREATE TRIGGER statement:
ON table_name
BEGIN
...
END;
You put the trigger name after the CREATE TRIGGER statement. The trigger name
should follow the naming convention [trigger time]_[table name]_[trigger event], for
example before_employees_update.
Trigger activation time can be BEFORE or AFTER. You must specify the activation time
when you define a trigger. You use the BEFORE keyword if you want to process action
prior to the change is made on the table and AFTER if you need to process action after
the change is made.
The 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, you have to define multiple triggers, one for each event.
A trigger must be associated with a specific table. Without a table trigger would not
exist therefore you have to specify the table name after the ON keyword.
50
YCA412/YCF412/YCI412-Database Management Systems Laboratory
You place the SQL statements between BEGIN and END block. This is where you
define the logic for the trigger.
1) Row Level Triggers: Row level trigger executes each time when an row is affected. If
zero rows affected then no row level trigger will execute. Suppose if you want to delete one
employye from emp table whose department is HR and you want as soon as employee deleted
from emp table the count in dept table from HR section should be reduce by 1 then row level
trigger will execute.
2) Statement Level Triggers: This kind of trigger fires when a SQL statement affects the
rows of the table. The trigger activates and performs its activity irrespective of number of
rows affected due to SQL statement.
Procedure:
To perform below trigger query you have refer previous table employees. Table is as follows:
+ + + +
| id | employee_no | lastname |
+ + + +
| 101 | 1 | patil |
| 102 | 2 | chavan |
| 103 | 4 | Pawar |
+ + + +
Show Trigger
51
YCA412/YCF412/YCI412-Database Management Systems Laboratory
-> $$
+ + + +
+
-+ + + + + +
+
+ + + +
+
-+ + + + + +
+
+ + + +
+
-+ + + + + +
+
-> $$
+ + + + + +
+ + + + + +
+ + + + + +
52
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
53
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
54
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Title Implement aggregation and indexing with suitable example using MongoDB
Theory:
AGGREGATION
Aggregations operations process data records and return computed results. Aggregation
operations group values from multiple documents together, and can perform a variety of
operations on the grouped data to return a single result. In sql count(*) and with group by is
an equivalent of mongodb aggregation.
55
YCA412/YCF412/YCI412-Database Management Systems Laboratory
INDEXING
Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan
every document of a collection to select those documents that match the query statement. This
scan is highly inefficient and require the mongodb to process a large volume of data.
Indexes are special data structures, that store a small portion of the data set in an easy to
traverse form. The index stores the value of a specific field or set of fields, ordered by the
value of the field as specified in index.
Procedure:
Aggregation Syntax:
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
> db.createCollection("staffit")
> db.staffit.find();
56
YCA412/YCF412/YCI412-Database Management Systems Laboratory
OUTPUT:
"ok" : 1 }
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
_id: ObjectId(7df78ad8902d)
title: 'NoSQL Overview',
description: 'No sql database is very fast',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 10
},
{
_id: ObjectId(7df78ad8902e)
title: 'Neo4j Overview',
description: 'Neo4j is no sql database',
by_user: 'Neo4j',
57
YCA412/YCF412/YCI412-Database Management Systems Laboratory
url: 'http://www.neo4j.com',
tags: ['neo4j', 'database', 'NoSQL'],
likes: 750
},
INDEXING
1. Creation of Index
db.collection.createIndex(keys, options)
keys document : For each field to index, a key-value pair with the field and the index order:
1 for ascending or -1 for descending.
options document: Optional. One or more key-value pairs that specify index options. For a
list of options,
1. Syntax:
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of field on which you want to create index and 1 is for ascending order.
To create index in descending order you need to use -1.
2. Example
> db.staffit.ensureIndex({id:1})
OUTPUT:
> db.staffit.find().sort({id:1})
58
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Unique Indexes
Unique indexes guarantee that, for a given key, every document in the collection will have a
unique value.
2. Deletion of Index
db.collection.dropIndex(index)
60
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
61
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
62
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Title Implement Map reduce operation with suitable example using MongoDB.
Theory:
MapReduce
Map-reduce is a data processing paradigm for condensing large volumes of data into useful
aggregated results. MongoDB uses mapReduce command for map-reduce operations.
MapReduce is generally used for processing large data sets. Everything described with count,
distinct, and group can be done with MapReduce, and more. It is a method of aggregation that
can be easily parallelized across multiple servers. It splits up a problem, sends chunks of it to
different machines, and lets each machine solve its part of the problem. When all of the
machines are finished, they merge all of the pieces of the solution back into a full solution.
The map function is a JavaScript function that associates or “maps” a value with a key and
emits the key and value pair during a map-reduce operation.
Steps of MapReduce :
First is map step: which maps an operation onto every document in a collection. That
operation could be either “do nothing” or “emit these keys with Xvalues.”
Second step called the shuffle step: keys are grouped and lists of emitted values are created
for each key.
Third is the reduce takes this list of values and reducesit to a single element. This element is
returned to the shuffle step until each key has a list containing a single value: the result.
2. Reduce Function (Ex. Reducing the total population count to single value)
3. Map Reduce Function ( it will create a new collection it contains the total population)
>db.collection.mapReduce(
function() {emit(key,value);}, //map function
63
YCA412/YCF412/YCI412-Database Management Systems Laboratory
The map-reduce function first queries the collection, then maps the result documents to emit
key-value pairs which is then reduced based on the keys that have multiple values.
map is a javascript function that maps a value with a key and emits a key-valur pair
reduce is a javscript function that reduces or groups all the documents having the
same key
out specifies the location of the map-reduce query result
query specifies the optional selection criteria for selecting documents
sort specifies the optional sort criteria
limit specifies the optional maximum number of documents to be returned
Procedure:
Consider the following document structure storing student status. The document stores name
of the student, satus and remark.
> db.studentstatus.find()
64
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Now, we will use a mapReduce function on our studentstatus collection to select all the pass
students, group them on the basis of name and status and count the number of pass student
using the following code −
> db.studentstatus.mapReduce(
... query:{status:"Pass"},
... out:"Pass_List_total"
... }
... )
{ "result" : "Pass_List_total",
"timeMillis" : 57,
"counts" : {
"input" : 3,
"emit" : 3,
"reduce" : 1,
"output" : 1
},
"ok" : 1,
The result shows that a total of 3 documents matched the query (status:"Pass"), the map
function emitted 3 documents with key-value pairs and finally the reduce function grouped
mapped documents having the same keys into 1.
65
YCA412/YCF412/YCI412-Database Management Systems Laboratory
To see the result of this mapReduce query use the find operator −
> db.studentstatus.mapReduce(
... query:{status:"Pass"},
... out:"Pass_List_total"
... }
...
... ).find()
The above query gives the following result which indicates that students rohan, sahil and
vrudhi have three stuatus in Pass state −
66
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
67
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
68
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Theory:
MongoDB
Database
Database is a physical container for collections. Each database gets its own set of files on the
file system. A single MongoDB server typically has multiple databases.
Collection
Doccument
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.
MongoDB use DATABASE_NAME is used to create database. The command will create a
new database, if it doesn't exist otherwise it will return the existing database.
Syntax:
>use DATABASE_NAME
1. Example:
69
YCA412/YCF412/YCI412-Database Management Systems Laboratory
If you want to create a database with name <mydb>, then use DATABASE statement would
be as follows:
>use student
switched to db student
>db
mydb
If you want to check your databases list, then use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
2. Syntax:
>db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database
3. Example:
First, check the list available databases by using the command show dbs
admin (empty)
dbs 0.0625GB
local 0.03125GB
prajakta 0.0625GB
test 0.0625GB
70
YCA412/YCF412/YCI412-Database Management Systems Laboratory
If you want to delete new database <mydb>, then dropDatabase() command would be as
follows:
switched to db test
> db.dropDatabase()
admin (empty)
dbs 0.0625GB
local 0.03125GB
prajakta 0.0625GB
Syntax:
>db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and used
to specify configuration of collection
71
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Options parameter is optional, so you need to specify only name of the collection. Following
is the list of options you can use:
While inserting the document, MongoDB first checks size field of capped collection, then it
checks max field.
Examples:
switched to db prajakta
> db.createCollection("stud_info")
{ "ok" : 1 }
72
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Pass_List_total
mycol
mycollection
stud_info
studentstatus
system.indexes
Syntax:
>db.COLLECTION_NAME.drop()
> db.stud_info.drop()
true
drop() method will return true, if the selected collection is dropped successfully otherwise it
will return false
To insert data into MongoDB collection, you need to use MongoDB's insert() or
save()method.
7. Syntax:
>db.COLLECTION_NAME.insert(document)
Example
> db.createCollection("stud_info")
73
YCA412/YCF412/YCI412-Database Management Systems Laboratory
{ "ok" : 1 }
OUTPUT:
> db.stud_info.insert({stud_id:101,name:'shravani',year:'FE'})
> db.stud_info.insert({stud_id:102,name:'yash',year:'SE'})
> db.stud_info.insert({stud_id:103,name:'rohit',year:'BE'})
> db.stud_info.insert({stud_id:104,name:'yamini',year:'TE'})
> db.stud_info.insert({stud_id:105,name:'swati',year:'TE'})
> db.stud_info.insert({stud_id:106,name:'amit',year:'BE'})
Here stud_info is our collection name. If the collection doesn't exist in the database, then
MongoDB will create this collection and then insert document into it. In the inserted
document if we don't specify the _id parameter, then MongoDB assigns an unique ObjectId
for this document.
find()
To query data from MongoDB collection, you need to use MongoDB's find() method.
8. Syntax
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non structured way.
To display the results in a formatted way, you can use pretty() method.
9. Syntax
>db.mycol.find().pretty()
Example:
a. Simple Find
> db.stud_info.find().pretty()
74
YCA412/YCF412/YCI412-Database Management Systems Laboratory
OUTPUT:
"_id" : ObjectId("57a96edf7f0d28785b0bfce1"),
"stud_id" : 101,
"name" : "shravani",
"year" : "FE"
"_id" : ObjectId("57a96ef37f0d28785b0bfce2"),
"stud_id" : 102,
"name" : "yash",
"year" : "SE"
"_id" : ObjectId("57a96f057f0d28785b0bfce3"),
"stud_id" : 103,
"name" : "rohit",
"year" : "BE"
"_id" : ObjectId("57a96f147f0d28785b0bfce4"),
"stud_id" : 104,
"name" : "yamini",
"year" : "TE"
75
YCA412/YCF412/YCI412-Database Management Systems Laboratory
"_id" : ObjectId("57a96f247f0d28785b0bfce5"),
"stud_id" : 105,
"name" : "swati",
"year" : "TE"
"_id" : ObjectId("57a96f327f0d28785b0bfce6"),
"stud_id" : 106,
"name" : "amit",
"year" : "BE"
Apart from find() method there is findOne() method, that returns only one document.
> db.stud_info.find({name:"rohit"}).pretty()
"_id" : ObjectId("57a96f057f0d28785b0bfce3"),
"stud_id" : 103,
"name" : "rohit",
"year" : "BE"
76
YCA412/YCF412/YCI412-Database Management Systems Laboratory
> db.stud_info.find({year:{$ne:"TE"}}).pretty()
OUTPUT:
"_id" : ObjectId("57a96edf7f0d28785b0bfce1"),
"stud_id" : 101,
"name" : "shravani",
"year" : "FE"
"_id" : ObjectId("57a96ef37f0d28785b0bfce2"),
"stud_id" : 102,
"name" : "yash",
"year" : "SE"
"_id" : ObjectId("57a96f057f0d28785b0bfce3"),
"stud_id" : 103,
"name" : "rohit",
"year" : "BE"
"_id" : ObjectId("57a96f327f0d28785b0bfce6"),
"stud_id" : 106,
"name" : "amit",
77
YCA412/YCF412/YCI412-Database Management Systems Laboratory
"year" : "BE"
> db.stud_info.find().count()
MongoDB's update() and save() methods are used to update document into a collection. The
update() method update values in the existing document while the save() method replaces the
existing document with the document passed in save() method.
Syntax
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
Example:
> db.stud_info.update({name:'amit'},{$set:{name:'rajesh'}})
> db.stud_info.find().pretty()
OUTPUT:
"_id" : ObjectId("57a96edf7f0d28785b0bfce1"),
"stud_id" : 101,
"name" : "shravani",
"year" : "FE"
78
YCA412/YCF412/YCI412-Database Management Systems Laboratory
"_id" : ObjectId("57a96ef37f0d28785b0bfce2"),
"stud_id" : 102,
"name" : "yash",
"year" : "SE"
"_id" : ObjectId("57a96f057f0d28785b0bfce3"),
"stud_id" : 103,
"name" : "rohit",
"year" : "BE"
"_id" : ObjectId("57a96f147f0d28785b0bfce4"),
"stud_id" : 104,
"name" : "yamini",
"year" : "TE"
"_id" : ObjectId("57a96f247f0d28785b0bfce5"),
"stud_id" : 105,
"name" : "swati",
"year" : "TE"
79
YCA412/YCF412/YCI412-Database Management Systems Laboratory
"_id" : ObjectId("57a96f327f0d28785b0bfce6"),
"name" : "rajesh",
"stud_id" : 106,
"year" : "BE"
MongoDB's remove() method is used to remove document from the collection. remove()
method accepts two parameters. One is deletion criteria and second is justOne flag
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example:
> db.stud_info.remove({'year':'BE'})
OUTPUT:
> db.stud_info.find().pretty()
"_id" : ObjectId("57a96edf7f0d28785b0bfce1"),
"stud_id" : 101,
"name" : "shravani",
"year" : "FE"
80
YCA412/YCF412/YCI412-Database Management Systems Laboratory
"_id" : ObjectId("57a96ef37f0d28785b0bfce2"),
"stud_id" : 102,
"name" : "yash",
"year" : "SE"
"_id" : ObjectId("57a96f147f0d28785b0bfce4"),
"stud_id" : 104,
"name" : "yamini",
"year" : "TE"
"_id" : ObjectId("57a96f247f0d28785b0bfce5"),
"stud_id" : 105,
"name" : "swati",
"year" : "TE"
If you don't specify deletion criteria, then mongodb will delete whole documents from the
collection. This is equivalent of SQL's truncate command.
>db.stud_info.remove()
>db.stud_info.find()
81
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Results:
82
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Conclusion:
Please Note:
83
YCA412/YCF412/YCI412-Database Management Systems Laboratory
Assessment
84
Department of Computer Science and Engineering
DEPARTMENT VISION
To build global leaders in computer science and engineering profession with research and
innovation skills to meet the needs of the industry and society.
DEPARTMENT MISSION
DM1: To provide academic environment which instill practical knowledge and use of modern
tools in computer science.
DM2: To promote the research by facilitating the cutting edge technologies and innovative
methods.
DM3: To develop centre of excellence for computer science and engineering to fulfill needs of
industry and society.
PEO1: Graduates will attain the expertise of analyzing and specifying the requirements for any
computing system as well as capable of modeling, designing, implementing and verifying a
computing system to meet specified requirements using contemporary tools
PEO2: Graduates will possess diversified professional skills for successful career.
PEO3: Graduates of the programme will have the competencies for communicating, planning,
coordinating, organizing, decision making and leading a team
PEO4: Graduates of the programme will have knowledge of professional, interpersonal and
ethical responsibility and will contribute to society through active research.
GRADUATE ATTRIBUTES
2. Analytical Skills: Identify, formulate, analyze and solve diverse engineering problems.
YCA412/YCF412/YCI412-Database Management Systems Laboratory
3. Design: Solution for complicated open–ended engineering problems and design the
components with appropriate standards to meet specified needs with proper attention to
public health, safety, environment and society.
87
YCA412/YCF412/YCI412-Database Management Systems Laboratory
PROGRAMME OUTCOMES
Programme Outcome
PO2 An ability to analyze a problem, interpret data, and define the computing system
requirements which would be appropriate to the solution.
PO4 An ability to apply creativity in the design of systems which would help to
investigate the complex problem and provide software solution.
PO5 An ability to use the computing techniques, skills, and modern system tools
necessary for practice as a CSE professional
PO6 An ability to analyze the local and global impact of computing on individuals,
organizations, and society
PO7 An ability to develop and use the software systems within realistic constraints
environmental, health and safety, manufacturability, and sustainability considerations
PO8 An ability in an understanding of professional, ethical, legal, security and social issues
and responsibilities
PO10 An ability to communicate effectively with a range of audiences by written and oral
ability to plan, organize and follow best practices and standards so that the project is
PO11 Completed as successfully by meeting performance, quality at CMM level, budget and
time
88
YCA412/YCF412/YCI412-Database Management Systems Laboratory
PSO1: Ability to employ latest computer languages, environments and platforms for
solving problems in the areas of emerging communication technologies.
PSO2 ability to use knowledge in data analytics and mining for industrial problems
89
Back Page