0% found this document useful (0 votes)
23 views

Final DBMS Lab Manual

Uploaded my DBMS lab manual
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Final DBMS Lab Manual

Uploaded my DBMS lab manual
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

Vidya Niketan Global Institute’s

VIDYA NIKETAN COLLEGE OF ENGINEERING


TAL.SANGAMNER DIST. A.NAGAR

DATABASE MANAGEMENT SYSTEM (310247)


LABORATORY MANUAL

DEPARMTENT OF COMPUTER ENGINEERING


Program Educational Objectives (PEOs)
PEO1: To develop students with a sound technical knowledge for a successful
career in industries, government organizations, academia and higher
studies and to demonstrate entrepreneurship.
PEO2: To prepare students with expertise in use of modeling, analysis and
programming software’s.
PEO3: To prepare students to work effectively as individual and as team
member in multidisciplinary projects and demonstrate managerial and
entrepreneurial skills.
Program Outcomes (POs)
PO1: Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.

PO2: Problem analysis: Identify, formulate, research literature, and analyze


complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.

PO3: 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.

PO4: Conduct investigations of complex problems: Use research-based


knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid
conclusions.

PO5: Modern tool Usage: Create, Select and apply appropriate techniques, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.

PO6: The Engineer and Society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.

PO7: 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.

PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

PO9: Individual and team work: Function effectively as an individual, and as a


member or leader in diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering


activities with the engineering community and with society at large, such as,
being able to comprehend and write effective reports and design documentation,
make effective presentations, and give and receive clear instructions.

PO11: Project management and finance: Demonstrate knowledge and


understanding of the engineering and management principles and apply these
to one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.

PO12: Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
Program Specific Outcomes (PSOs)
PSO1: Professional Skills-The ability to understand, analyze and develop
computer programs in the areasrelated to algorithms, system software,
multimedia, web design, big data analytics, and networking for efficient
design of computer-based systems of varying complexities.
PSO2: Problem-Solving Skills- The ability to apply standard practices and
strategies in software project development using open-ended
programming environments to deliver a quality product for business
success.
PSO3: Successful Career and Entrepreneurship- The ability to employ modern
computer languages, environments and platforms in creating innovative
career paths to be an entrepreneur and to have a zest for higher studies.

Objectives of Database Management Systems Laboratory


 To develop Database programming skills.
 To develop basic Database administration skills.
 To develop skills to handle NoSQL database.
 To learn, understand and execute process of software application development.

Course Outcomes (COs)


On completion of the course, learner will be able to

CO1: Design E-R Model for given requirements and convert the same into
database tables.
CO2: Design schema in appropriate normal form considering actual
requirements. CO3: Implement SQL queries for given requirements, using
different SQL concepts. CO4: Implement PL/SQL Code block for given
requirements.
CO5: Implement NoSQL queries using MongoDB.
CO6: Design and develop application considering actual requirements and
using database concepts.
LIST OF PRACTICALS
Page
Sr No Name of the Experiments
Number
s
1 ER Modeling and Normalization
1-6
SQL Queries:
a. Design and Develop SQL DDL statements which
2 demonstrate the use of SQL objects such as Table, View,
Index, Sequence, Synonym, different constraints etc.
7-15
b. Write at least 10 SQL queries on the suitable database
application using SQL DML statements.
SQL Queries – all types of Join, Sub-Query and View:
3 Write at least10 SQL queries for suitable database application 16-24
using SQL DML statements.
Unnamed PL/SQL code block: Use of Control structure and
Exception handling is mandatory.
Suggested Problem statement:
Consider Tables:
1. Borrower(Roll_no, Name, Date of Issue, Name of Book, Status)
2. Fine(Roll_no, Date, Amt)
Accept Roll_no and Name of Book from user.
4 Check the number of days (from date of issue). 25-31
If days are between 15 to 30 then fine amount will be Rs 5per day.
If no. of days>30, per day fine will be Rs 50 per day and for
days less than 30, Rs. 5 per day. After
submitting the book, status will change from I to R.
If condition of fine is true, then details will be stored into fine
table.
Also handles the exception by named exception handler or
user define exception handler.
Named PL/SQL Block: PL/SQL Stored Procedure and
Stored Function.
Write a Stored Procedure namely proc_Grade for the
categorization of student. If marks scored by students in
examination is <=1500 and marks>=990 then student will be
5 placed in distinction category if marks scored are
between 989 and900 category is first class, if marks899and
32-37
825 category is Higher Second Class.
Write a PL/SQLblock to use procedure created with
above requirement.
Stud_Marks(name, total_marks)
Result(Roll,Name, Class)
Cursors :( All types: Implicit, Explicit, Cursor FOR Loop,
Parameterized Cursor)
Write a PL/SQL block of code using parameterized Cursor that
6 will merge the data available in the newly created 38-43
table N_Roll Call 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.
atabase Trigger (All Types: Row level and Statement level
7 triggers, Before and
After Triggers).
44-53
Write a database trigger on Library table. The System should
keep
track of the records that are being updated or
deleted. The old value of updated or deleted records should be
added in
Library_Audit table.. Student_Marks(name,
total_marks) Result(Roll,Name, Class).
Database Connectivity:
8 Write a program to implement MySQL/Oracle database
connectivity with any front end language to
54-61
implement Database navigation operations (add, delete, edit etc.)
MongoDB Queries:
9 Design and Develop MongoDB Queries using CRUD operations.
(Use CRUD operations, SAVE method, logical
62-67
operators etc.).
MongoDB – Aggregation and Indexing:
10 Design and Develop MongoDB Queries using aggregation 68-72
and indexing with suitable example using MongoDB.
MongoDB – Map-reduces operations:
11 Implement Map reduces operation with suitable example 73-76
using MongoDB.
Database Connectivity:
12 Write a program to implement MySQL/Oracle database
connectivity with any front end language to implement
77-79
Database navigation
operations (add, delete, edit etc.)
Assignment No .1

Title of Assignment: ER Modeling and Normalization

Decide a case study related to real time application in group of 2-3 students and formulate a problem statement
for application to be developed. Propose a Conceptual Design using ER features using tools like ERD plus, ER Win
etc. (Identifying entities, relationships between entities, attributes, keys, cardinalities, generalization,
specialization etc.) Convert the ER diagram into relational tables and normalize Relational data model.

Note: Student groups are required to continue same problem statement throughout all the assignments in order
to design and develop an application as a part Mini Project. Further assignments will be useful for students to
develop a backend for system. To design front end interface students should use the different concepts learnt in
the other subjects also.

Course Objective: To develop Database programming skills

Course Outcome:

C306.1 Design E-R Model for given requirements and convert the same into

database tables C306.2 Design schema in appropriate normal form considering

actual requirements Software Required: - Any tool for drawing ER diagram

Theory: -
Entity Relationship (E R) Model : The Entity Relationship (ER) model is one of several high-level, or
semantic, data models used in database design. The goal is to create a simple description of the data that
closely matches how users and developers think of the data
A database can be modeled as : a collection of entities, relationship among
entities. An Entity is real-world object that exists and is distinguishable from
other objects. A relationship is an association among several (Two or more)
entities.
Entities are represented by means of their properties, called attributes.
An entity set is a set of entities of the same type that share the same
properties. Each entity set has a Key.
Each Attribute has a Domain.
Types of Attributes
Simple attribute − Simple attributes are atomic values, which cannot be divided
further. For example, a Customer's ID number is an atomic value of 6 digits.
Composite attribute − Composite attributes are made of more than one simple attribute.
VNCOE BOTA

1
For example, a customer's complete name may have first-name, middle-initial and last
-name. Single-value attribute − Single-value attributes contain single value.
For example − Customer_ID, Social_Security_Number.
Multi-value attribute − Multi-value attributes may contain more than one
values. For example, a person can have more than one phone number,
email_address, etc.
Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but
their values are derived from other attributes present in the database. For example, age can be derived
from date_of_birth

Example of ER diagram

VNCOE BOTA

2
Relational Model

The relational model is a depiction of how each piece of stored information relates to the other stored
information. It shows how tables are linked, what type of the links are between tables, what keys are used, what
information is referenced between tables. It’s an essential part of developing a normalized database structure to
prevent repeat and redundant data storage. Different types of keys:  A super key is a set of one or more
attributes which; taken collectively, allow us to identify uniquely an entity in the entity set.  A primary key is a
candidate key(there may be more than one) chosen by the DB designer to identify entities in an entity set.  A
super key may contain extraneous attributes, and we are often interested in the smallest super key. A super key
for which no subset is a super key is called a candidate key.  An entity does not posses sufficient attributes to
form a primary ket is called a weak entity set. One that does have a primary key is called a strong entity set.  A
foreign key is a field in a relational table that matches the primary key column of another table. The foreign key
can be used to cross-reference tables.

Normalization

Database normalization is a technique for designing relational database tables to minimize duplication of
information and, in so doing, to safeguard the database against certain types of logical or structural problems,
namely data anomalies. In this we will write the normalization tables that is entities of “Roadway Travels.”
Normalization: In relational databases, normalization is a process that eliminates redundancy, organizes data
efficiently; Normalization is the process of efficiently organizing data in a database. There are two goals of the
normalization process: eliminating redundant data(for example, storing the same data in more than one table)
and ensuring data dependencies make sense(only storing related data in a tablet). Both of these are worthy goals
as they reduce the amt of space a database consumes and ensure that data is logically stores. The Normal Form:
the database community has developed a series of guidelines for ensuring that databases are normalized.

VNCOE BOTA

3
These are referred to as normal forms and are numbered from one ( the lowest form to

VNCOE BOTA

4
normalization, referred to as first form or INF) through five(fifth normal form of SNF). In practical applications,
you’ll often see INF, 2NF, and 3NF along with occasional 4NF. Fifth normal form is very rarely seen and won’t be
discussed in this article. It’s important to point out that they are guidelines and guidelines only. Occasionally, it
becomes necessary to stray from them to meet practical business requirements. However, when variations take
place, it’s extremely important to evaluate any possible requirements they could have on your system and
account for possible inconsistencies. That said, let’s explore the normal form.

Conclusion:

Students are able to design ER diagram and convert it into table with Normalized tables.

VNCOE BOTA

5
Activity to be Submitted by Students

1. Draw an E-R Diagram For an ATM System.


2. Convert below diagram to tables.

3. Normalize below table till 3 NF

4.

VNCOE BOTA

6
VNCOE BOTA

7
DBMS ThirdYear Computer
Assignment No .2

Title of Assignment: SQL Queries:


a. Design and Develop SQL DDL statements which demonstrate the use of SQL objects suchas Table,
View, Index, Sequence, Synonym, different constraints etc.
b. Write at least 10 SQL queries on the suitable database application using SQL
DMLstatements. Note: Instructor will design the queries which demonstrate the use
of concepts like Insert,
Select, Update, Delete with operators, functions, and set operator etc.

Course Objective:

Implement SQL queries for given requirements, using different SQL concepts

Course Outcome:

C306.3 Implement SQL queries for given requirements, using different SQL concepts

Software Required: - Mysql

Theory: -
Database: - a structured set of data held in a computer, especially one that is accessible in various ways.
Database System: - A database management system (DBMS) is a computer software application that
interactswith the user, other applications, and the database itself to capture and analyze data. A general-
purpose DBMS isdesigned to allow the definition, creation, querying, update, and administration of
databases.
A database management system (DBMS) is a software tool that makes it possible to organize data in a
database.A database is a collection of information that is organized so that it can be easily accessed,
managed and updated.

SQL: The Language of Database Access: -


Structured Query Language (SQL) is a standardized programming language for accessing and
manipulating databases. In an RDBMS like MySQL, Sybase, Oracle, or IMB DM2, SQL writes programming
that can manage data and stream data processing. SQL is like a database’s own version of a server-side
script and is responsible for:
 Executing queries, which are “questions” asked of the database
 Retrieving data
 Editing data: inserting, updating, deleting, or creating new records
 Creating views

=VNCOE BOTA

8
DBMS ThirdYear Computer
 Setting permissions
 Creating new databases
SQL is a standard programming language, but has a number of variations—including some databases’
own proprietary SQL extensions.
Top 7 open source relational databases: -
CUBRID, Firebird, MariaDB, MySQL, Postgre SQL, SQLite
RDBMS Terminology
Before we proceed to explain the MySQL database system, let us revise a few definitions related to the
database.
 Database − A database is a collection of tables, with related data.
 Table − A table is a matrix with data. A table in a database looks like a simple spreadsheet.
 Column − One column (data element) contains data of one and the same kind, for example
the column postcode.
 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 can not occur twice in one table. With a key,
you can only find 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.
 Index − An index in a database resembles an index at the back of a book.
 Referential Integrity − Referential Integrity makes sure that a foreign key value always
points to an existing row.
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 handles a large subset of the functionality
of the most expensive and powerful database packages.
 MySQL uses a standard form of the well-known SQL data language.
 MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.

=VNCOE BOTA

9
DBMS ThirdYear Computer
 MySQL works very quickly and works well even with large data sets.
 MySQL is very friendly to PHP, the most appreciated language for web development.

=VNCOE BOTA

10
DBMS ThirdYear Computer
 MySQL supports large databases, up to 50 million rows or more in a table. The default file size

limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
 MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.
Administrative MySQL Command
Here is the list of the important MySQL commands, which you will use time to time to work with MySQL
database −
 USE Databasename − This will be used to select a database in the MySQL workarea.
 SHOW DATABASES − Lists out the databases that are accessible by the MySQL DBMS.
 SHOW TABLES − Shows the tables in the database once a database has been selected
with the use command.
 SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes, key
information, whether NULL is permitted, defaults, and other information for a table.
 SHOW INDEX FROM tablename − Presents the details of all indexes on the table, including
the PRIMARY KEY.

MySQL Connection Using MySQL Binary


You can establish the MySQL database using the mysql binary at the command prompt.
=VNCOE BOTA

11
DBMS ThirdYear Computer
Example
Here is a simple example to connect to the MySQL server from the command
prompt − [root@host]#mysql-u root -p
Enter password:******
This will give you the mysql> command prompt where you will be able to execute any SQL command.
Following is the result of above command −
The following code block shows the result of above code −
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2854760 to server version:
5.0.9

Type 'help;' or '\h' for help.Type '\c' to clear the buffer.


In the above example, we have used root as a user but you can use any other user as well. Any user will
be able to perform all the SQL operations, which are allowed to that user.
You can disconnect from the MySQL database any time using the exit command at mysql>
prompt. mysql> exit
Bye
USE DatabaseName;
Always the database name should be unique within the RDBMS.

DROP DATABASE databaseName -- Delete the database


(irrecoverable!) DROP DATABASE IF EXISTS databaseName -- Delete if it
exists
CREATE DATABASE databaseName -- Create a new database
CREATE DATABASE IF NOT EXISTS databaseName -- Create only if it does not
exists SHOW DATABASES -- Show all the databases in this server
USE databaseName -- Set the default (current)
database SELECT DATABASE() -- Show the default
database
SHOW CREATE DATABASE databaseName -- Show the CREATE DATABASE statement

-- Table-Level
DROP TABLE [IF EXISTS] tableName, ... CREATE
TABLE [IF NOT EXISTS] tableName (
=VNCOE BOTA

12
DBMS ThirdYear Computer
columnName columnType columnAttribute, ...
PRIMARY KEY(columnName),
FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)

=VNCOE BOTA

13
DBMS ThirdYear Computer

)
SHOW TABLES -- Show all the
tables in the default
databaseDESCRIBE|DESC tableName
-- Describe the details for a table
ALTER TABLE tableName ... -- Modify a table, e.g., ADD COLUMN and
DROP COLUMNALTER TABLE tableName ADD columnDefinition
ALTER TABLE tableName DROP columnName
ALTER TABLE tableName ADD FOREIGN KEY (columnNmae) REFERENCES
tableName (columnNmae)ALTER TABLE tableName DROP FOREIGN KEY
constraintName
SHOW CREATE TABLE tableName -- Show the CREATE TABLE statement for
this tableName

Data Manipulation Language (DML)


Allows you to modify the database instance by inserting, modifying, and deleting its data. It is
responsible for performing all types of data modification in a database. There are three basic
constructs which allow database program and user to enter data and information are:
Here are some important DML commands in SQL:
INSERT
UPDATE
DELETE

INSERT:
This is a statement is a SQL query. This command is used to insert data into the row of a
table. Syntax:

INSERT INTO TABLE_NAME (col1, col2, col3, col N)


VALUES (value1, value2, value3, valueN);
Or
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, valueN);
For example:

INSERT INTO students (RollNo, FIrstName, LastName) VALUES ('60', 'Tom', Erichsen');

UPDATE:
This command is used to update or modify the value of a column in the

table. Syntax:

UPDATE table_name SET [column_name1= value1,. column_nameN = valueN] [WHERE


CONDITION]
For example:

UPDATE students
SET FirstName = 'Jhon', LastName= 'Wick'
WHERE StudID = 3;
DELETE:
This command is used to remove one or more rows from a table.

VNCOE BOTA

11
DBMS ThirdYear Computer

DELETE FROM table_name [WHERE condition];


For example:

DELETE FROM students


WHERE FirstName = 'Jhon';
I. Set Operators

Set operators combine the results of two component queries into a single result.
Queries containing set operators are called compound queries. The lists of SQL
set operators are "UNION [ALL], INTERSECT, MINUS Operators".You can combine
multiple queries usingthe set operators UNION, UNION ALL, INTERSECT, and
MINUS. All set operators have

VNCOE BOTA

12
DBMS ThirdYear Computer

equal precedence. If a SQL statement contains multiple set operators, then


Oracle Databaseevaluates them from the left to right unless parentheses
explicitly specify another order.Thecorresponding expressions in the select lists
of the component queries of a compound querymust match in number and must
be in the same datatype group (such as numeric or character).

If component queries select character data, then the datatype of the return values
aredetermined as follows:

 If both queries select values of datatype CHAR of equal length, then the
returned values have datatype CHAR of that length. If the queries select
values of CHAR with different lengths, then the returned value is VARCHAR2
with the length of the larger CHAR value.
 If either or both of the queries select values of datatype VARCHAR2,
then the returned values have datatype VARCHAR2.

If component queries select numeric data, then the datatype of the return values is
determinedby numeric precedence:

 If any query selects values of type BINARY_DOUBLE, then the returned values
have datatype BINARY_DOUBLE.
 If no query selects values of type BINARY_DOUBLE but any query selects
values of type BINARY_FLOAT, then the returned values have datatype
BINARY_FLOAT.
 If all queries select values of type NUMBER, then the returned values
have datatype NUMBER.

In queries using set operators, Oracle does not perform implicit conversion
across datatype groups. Therefore, if the corresponding expressions of
component queries resolve to both character data and numeric data, Oracle
returns an error to fetch only unique records insteadof fetching duplicate
records.

II. SQL Functions

SQL functions are built into Oracle Database and are available for use in various
appropriate SQL statements. Do not confuse SQL functions with user-defined
functions written in PL/SQL.If you call a SQL function with an argument of a
datatype other than the datatype expected by the SQL function, then Oracle
attempts to convert the argument to the expected datatype before performing the
SQL function. If you call a SQL function with a null argument, then the SQL function
automatically returns null.

1. Single-Row Functions
Single-row functions return a single result row for every row of a queried table or
view. These functions can appear in
select lists, WHERE clauses, STARTWITH and CONNECT BY clauses, and HAVING
clauses.

2. Character Functions Returning Character Value


Character functions that return character values return values of the following
VNCOE BOTA

13
DBMS ThirdYear Computer
datatypesunless otherwise documented:

VNCOE BOTA

14
DBMS ThirdYear Computer

 If the input argument is CHAR or VARCHAR2, then the value returnedis VARCHAR2.
 If the input argument is NCHAR or NVARCHAR2, then the value returnedis NVARCHAR2.

The length of the value returned by the function is limited by the maximum length of thedatatype
returned.

 For functions that return CHAR or VARCHAR2, if the length of the return value exceeds the limit,
then Oracle Database truncates it and returns the result without an error message.
 For functions that return CLOB values, if the length of the return values exceeds the limit, then
Oracle raises an error and returns no data.

3. Datetime Functions

Datetime functions operate on date (DATE), timestamp(TIMESTAMP,


TIMESTAMP WITH TIME ZONE,and TIMESTAMP WITH L OCAL TIM
E ZONE), and interval (INTERVAL DAY TO SECOND, INTERVAL YEAR )
TO MONT
values. Some of the datetime functions were designed for the Oracle DATE datatype
(ADD_MONTHS,
CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If you

provide a timestamp value as their argument, Oracle Database internally converts the input type toa DATE
value and returns a DATE value. The exceptions are the MONTHS_BETWEEN function,which returns a
number, and the ROUND and TRUNC functions, which do not accept timestamp or interval values at all. The
remaining datetime functions were designed to accept any of the three types of data (date, timestamp, and
interval) and to return a value of one of these types.

Conclusion:

Students are able to implement SQL queries for given requirements, using different SQL concepts

Activity to be Submitted by Students

1. Write a SQL statement to create a table job_history including columns employee_id, start_date,
end_date, job_id and department_id and make sure that, the employee_id column does not contain any
duplicate value at the time of insertion and the foreign key column job_id contain only those values
which are exists in the jobs table.

Here is the structure of the table jobs;

+ + + + + + +
| Field | Type | Null | Key | Default | Extra |
+ + + + + + +
| JOB_ID | varchar(10) | NO | PRI | | |
| JOB_TITLE | varchar(35) | NO | | NULL | |
| MIN_SALARY | decimal(6,0) | YES | | NULL | |
| MAX_SALARY | decimal(6,0) | YES | | NULL | |
VNCOE BOTA

15
+ DBMS + + + + ThirdYear
+ Computer
+

VNCOE BOTA

16
DBMS ThirdYear Computer

2. Write a SQL statement to create a table employees including columns employee_id, first_name,
last_name, job_id, salary and make sure that, the employee_id column does not contain any duplicate
value at the time of insertion, and the foreign key column job_id, referenced by the column job_id of jobs
table, can contain only those values which are exists in the jobs table. The InnoDB Engine have been
used to create the tables. The specialty of the statement is that, The ON DELETE NO ACTION and the
ON UPDATE NO ACTION actions will reject the deletion and any updates.

3. Consider the following schema for a LibraryDatabase: BOOK (Book_id, Title, Publisher_Name, Pub_Year)
BOOK_AUTHORS (Book_id, Author_Name) PUBLISHER (Name, Address, Phone) BOOK_COPIES (Book_id,
Branch_id, No- of_Copies) BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date) LIBRARY_BRANCH
(Branch_id, Branch_Name, Address) Write SQL queries to

1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies in each branch,etc.

2. Get the particulars of borrowers who have borrowed more

than 3 books, but from Jan 2017 to Jun2017

3. Delete a book in BOOK table. Update the contents of other tables to reflect this data manipulationoperation.

4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple query.

5. Create a view of all books and its number of copies that are currently available in the Library.

VNCOE BOTA

17
Assignment No .3

Title of Assignment: SQL Queries – all types of Join, Sub-Query and View:

Write at least10 SQL queries for suitable database application using SQL DML
statements. Note: Instructor will design the queries which demonstrate the use of
concepts like all types of Join, Sub-Query and View
Course Objective:

Implement SQL queries for given requirements, using different SQL concepts

Course Outcome:

C306.3 Implement SQL queries for given requirements, using different SQL concepts

Software Required: - Mysql

Theory: -
Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as
single set of data. SQL Join is used for combining column from two or more tables by
using values common to both tables. Join Keyword is used in SQL queries for joining
two or more tables. Minimum required condition for joining table, is (n-1) where n, is
number of tables. A table can also join to itself known as, Self Join.
Types of Join:-
The following are the types of JOIN that we can use in SQL.
 Inner
 Outer
 Left
 Right

Cross JOIN or Cartesian Product


This type of JOIN returns the cartesian product of rows from the tables in Join. It will
return a table which consists of records which combines each row from the first table
with each row of the second table.
Cross JOIN Syntax is,
SELECT column-name-
list from table-name1
CROSS JOIN
table-name2;

INNER Join or EQUI Join


JaTihhisinisdaCsiomlplelegJeOo
INf iEnnwghiinch
e et hreinregs,uKlt uisrabnased on matched data as per the equality condition

16
specified in the query.
Inner Join Syntax is,
SELECT column-name-
list from table-name1
INNER JOIN
table-name2

WHERE table-name1.column-name = table-name2.column-name;

Jaihind College of Engineering,Kuran

17
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and
same datatype present in both the tables to be joined.
Natural Join Syntax is,
SELECT *
from table-name1

NATURAL JOIN
table-name2;

Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
 Left Outer Join
 Right Outer Join
 Full Outer Join
Left Outer Join
The left outer join returns a result table with the matched data of two tables then
remaining rows of the left table and null for the right table's column.
Left Outer Join syntax is,
SELECT column-name-
list from table-name1
LEFT OUTER JOIN
table-name2

on table-name1.column-name = table-name2.column-
name; Left outer Join Syntax for Oracle is,
select column-
name- listfrom
table-name1, table-
name2

on table-name1.column-name = table-name2.column-name(+);
Left Outer Join query will be,

SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id=class_info.id);


The result table will look like,
ID NAME ID ADDRESS
1 Abhi 1 DELHI
2 Adam 2 MUMBAI

18
3 A le x
J a ihind College of E ng in eering,Kuran 3 CHENNAI

19
4 Anu Null Null

20
5 Ashish Null Null

Right Outer Join


The right outer join returns a result table with the matched data of two tables then
remaining rows of the right table and null for the left table's columns.
select column-name-
list from table-name1
RIGHT OUTER JOIN

table-name2
on table-name1.column-name = table-name2.column-
name; Right outer Join Syntax for Oracle is,
select column-
name- listfrom
table-name1, table-
name2

on table-name1.column-name(+) = table-name2.column-name;

SQL Subquery
Subquery or Inner query or Nested query is a query in a query. SQL subquery is usually
added in the WHERE Clause of the SQL statement. Most of the time, a subquery is used
when you know how to search for a value using a SELECT statement, but do not know
the exact value in the database.
Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the following SQL statements along with the comparision
operators like =, <, >, >=, <= etc.
 SELECT
 INSERT
 UPDATE
 DELETE
21
 SQL Subquery Example:

22
 1) Usually, a subquery should return only one record, but sometimes it can
also return multiple records when used with operators LIKE IN, NOT IN in the
where clause. The query syntax would be like,
 SELECT first_name, last_name,
subject FROM student_details
WHERE games NOT IN ('Cricket', 'Football');
 Subquery output would be similar to:

VNCOE BOTA

23
first_name last_name subject

Shekar Gowda
Badminton Priya Chandra
Chess
SQL Subquery; INSERT Statement
3) Subquery can be used with INSERT statement to add rows of data from one or more
tables to another table. Lets try to group all the students who study Maths in a table
'maths_group'. INSERT INTO maths_group(id, name)
SELECT id, first_name || ' ' || last_name
FROM student_details WHERE subject= 'Maths'
SQL Subquery; SELECT Statement
4) A subquery can be used in the SELECT statement as follows. Lets use the
product and order_items table defined in the sql_joins section.
select p.product_name, p.supplier_name, (select order_id from order_items where
product_id = 101) as order_id from product p where p.product_id = 101
product_name supplier_name order_id

Television Onida 5103


Correlated Subquery
A query is called correlated subquery when both the inner query and the outer query are
interdependent. For every row processed by the inner query, the outer query is processed
as well. The inner query depends on the outer query before it can be processed.
SELECT p.product_name FROM product p
WHERE p.product_id = (SELECT o.product_id FROM order_items o
WHERE o.product_id = p.product_id);
Subquery Notes
Nested Subquery
1) You can nest as many queries you want but it is recommended not to nest
more than 16 subqueries in oracle
Non-Corelated Subquery
2) If a subquery is not dependent on the outer query it is called a non-correlated subquery
Subquery Errors
3) Minimize subquery errors: Use drag and drop, copy and paste to avoid running
subqueries with spelling and database typos. Watch your multiple field SELECT comma
VNCOE BOTA

24
use, extra or to few getting SQL error message "Incorrect syntax".

VNCOE BOTA

25
DBMS ThirdYear Computer

SQL Subquery Comments


Adding SQL Subquery comments are good habit (/* your command comment */) which can saveyou
time, clarify your previous work .. results in less SQL headaches.
SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or more tablescan be
seen. Views do not contain data of their own. They are used to restrict access to the database or to
hide data complexity. A view is stored as a SELECT statement in the database.
DML operations on a view like INSERT, UPDATE, DELETE affects the data in the originaltable
upon which the view is based.
The Syntax to create a sql view is
CREATE VIEW view_nameAS
SELECT column_list
FROM table_name [WHERE condition];
 view_name is the name of the VIEW.
 The SELECT statement is used to define the columns and rows that you want to displayin the view.
 For Example: to create a view on the product table the sql query would be
like,CREATE VIEW view_product
AS SELECT product_id, product_nameFROM
product;

Conclusion:

Students are able to implement SQL queries all types of Join, Sub-Query and View for given requirements,
using different SQL concepts

Activity to be Submitted by Students

1. Consider the schema for MovieDatabase:


ACTOR (Act_id, Act_Name, Act_Gender)
DIRECTOR (Dir_id, Dir_Name, Dir_Phone)
MOVIES (Mov_id, Mov_Title, Mov_Year, Mov_Lang,
Dir_id) MOVIE_CAST (Act_id, Mov_id, Role) RATING
(Mov_id,
Rev_Stars) Write SQL queries to
1. List the titles of all movies directed by‘Hitchcock’.
2. Find the movie names where one or more actors acted in two or moremovies.
3. List all actors who acted in a movie before 2000 and also in a

VNCOE BOTA

26
DBMS ThirdYear Computer

movieafter 2015 (use JOINoperation).


4. Find the title of movies and number of stars for each movie that
has at least one rating and find the highest number of stars that
movie received. Sort the result by movie title.
5. Update rating of all movies directed by ‘Steven Spielberg’ to5.

2. Apply Self Join to Student(Roll,name,address,branch,Class)

3. From the following table, create a view for all salespersons. Return salesperson ID, name, and city.

Sample table: salesman

VNCOE BOTA

27
Assignment No .4

Title of Assignment: Unnamed PL/SQL code block: Use of Control structure and Exception
handling ismandatory.
Suggested Problem statement:
Consider Tables:
1. Borrower(Roll_no, Name, Date of Issue, Name of Book, Status)
2. Fine(Roll_no, Date, Amt)
Accept Roll_no and Name of Book from user.
Check the number of days (from date of
issue).
If days are between 15 to 30 then fine amount will be Rs 5per day.
 If no. of days>30, per day fine will be Rs 50 per day and for days less than 30, Rs. 5
perday. After submitting the book, status will change from I to R.
 If condition of fine is true, then details will be stored into fine table.
 Also handles the exception by named exception handler or user define exception handler.
OR
Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 5 to 9.
Store the radius and the corresponding values of calculated area in an empty table named areas,
consisting of two columns, radius and area.
Note: Instructor will frame the problem statement for writing PL/SQL block in line with above
statement

Course Objective:

Implement PL/SQL Code block for given requirements

Course Outcome:

C306.4 Implement PL/SQL Code block for given requirements

Software Required: - Mysql

Theory: -

A. Control Structures: - PL/SQL allows the use of an IF statement to control the execution of a
block of code. In PL/SQL, the IF -THEN - ELSIF - ELSE - END IF construct in code blocks allow
specifying certain conditions under which a specific block of code should be execute PL/SQL
Control Structures are used to control flow of execution. PL/SQL provides different kinds of
statements to provide such type of procedural capabilities. These statements are almost
same as that of provided by other languages. The flow of control statements can be
classified into the following categories:
 Conditional Control
VNCOE BOTA

28
 Iterative Control
 Sequential Control

VNCOE BOTA

29
PL/SQL allows the use of an IF statement to control the execution of a block
of code. In PL/SQL, the IF -THEN - ELSIF - ELSE - END IF construct in code blocks allow
specifying certain conditions under which a specific block of code should be executed.

VNCOE BOTA

30
Syntax

IF < Condition > THEN

< Action >

ELSIF <Condition> THEN

< Action >

ELSE < Action >

END IF;

Iterative Control :

Iterative control indicates the ability to repeat or skip sections of a code


block. A loop marks a sequence of statements that has to be repeated. The keyword
loop has to be placed before the first statement in the sequence of statements to be
repeated, while the keyword end loop is placed immediately after the last
statement in the sequence. Once a loop begins to execute, it will go on forever.
Hence a conditional statement that controls the number of times a loop is
executed always accompanies loops. PL/SQL supports the following structures
for iterative control:

Simple loop : In simple loop, the key word loop should be placed before the first
statement in the sequence and the keyword end loop should be written at the end of
the sequence to end the loop.

Syntax:

Loop

< Sequence of statements >

End loop;
1. WHILE loop

The while loop executes commands in its body as long as the condition remains true
VNCOE BOTA

31
Syntax

WHILE < condition >


LOOP

< Action >

2. The FOR Loop

The FOR loop can be used when the number of iterations to be executed are known.

Syntax :

FOR variable IN [REVERSE] start..end


LOOP
< Action >
END LOOP;

The variable in the For Loop need not be declared. Also the increment value cannot be
specified. The For Loop variable is always incremented by 1.
3. Sequential Control :

The GOTO Statement


The GOTO statement changes the flow of control within a PL/SQL block. This
statement allows execution of a section of code, which is not in the normal flow of
control. The entry point into such a block of code is marked using the tags «userdefined
name». The GOTO statement can then make use of this user-defined name to jump into
that block of code for execution.

Syntax :

GOTO jump;
....
<<jump>>

VNCOE BOTA

32
B. Exceptions

An Exception is an error situation, which arises during program execution. When an


error occurs exception is raised, normal execution is stopped and control transfers to
exception handling part. Exception handlers are routines written to handle the exception.
The exceptions can be internally defined (system-defined or pre-defined) or User-
defined exception.

Syntax:

EXCEPTION

WHEN <ExceptionName> THEN

<User Defined Action To Be Carried Out>

Predefined exception:

Predefined exception is raised automatically whenever there is a violation of Oracle


coding rules. Predefined exceptions are those like ZERO_DIVIDE, which is raised
automatically when we try to divide a number by zero. Other built-in exceptions are
given below. You can handle unexpected Oracle errors using OTHERS handler. It can
handle all raised exceptions that are not handled by any other handler. It must always be
written as the last handler in exception block.

Exception Raised when....

DUP_VAL_ON_INDEX When you try to insert a duplicate value into a unique column.

INVALID_CURSOR It occurs when we try accessing an invalid cursor.

INVALID_NUMBER On usage of something other than number in place of number value.

VNCOE BOTA

33
VNCOE BOTA

34
DBMS ThirdYear Computer

LOGIN_DENIED At the time when user login is denied.

TOO_MANY_ROWS When a select query returns more than one row and the destination
variable can take only single value.

VALUE_ERROR When an arithmetic, value conversion, truncation, or constraint


error occurs.

CURSOR_ALREADY_OPEN Raised when we try to open an already open cursor.

Predefined exception handlers are declared globally in package STANDARD. Hence we


need not have to define them rather just use them. The biggest advantage of exception
handling is it improves readability and reliability of the code. Errors from many statements
of code can be handles with a single handler. Instead of checking for an error at every
point we can just add an exception handler and if any exception is raised it is handled by
that. For checking errors at a specific spot it is always better to have those statements in
a separate begin – end block.

User Defined Exception Handling:


To trap business rules being violated the technique of raising user-defined exceptions and then
handling them, is used. User-defined error conditions must be declared in the declarative part of
any PL/SQL block. In the executable part, a check for the condition that needs special attention is
made. If that condition exists, the call to the user-defined exception is made using a RAISE
statement. The exception once raised is then handled in the Exception handling section of the
PL/SQL code block.

Syntax:

DECLARE

< ExceptionName > EXCEPTION ;

BEGIN

<SQL Sentence >;


VNCOE BOTA

35
DBMS ThirdYear Computer

Conclusion:

Students are able to Implement PL/SQL Code block for given requirements

Activity to be Submitted by Students

1. Write a PL/SQL block which accepts a cleaner number and returns the cleaners name and salary and
update this cleaner’s details by increasing salary by 10%. Use Exception Handling.

2. Write a PL/SQL block to find Largest of three numbers

VNCOE BOTA

36
Assignment No .5

Title of Assignment: Named PL/SQL Block: PL/SQL Stored Procedure and Stored Function.
Write a Stored Procedure namely proc_Grade for the categorization of student. If marks scored by
students in examination is <=1500 and marks>=990 then student will be placed in distinction category if
marks scored are between 989 and900 category is first class, if marks899and 825 category is Higher
Second Class.
Write a PL/SQLblock to use procedure created with above
requirement. Stud_Marks(name, total_marks)
Result(Roll,Name, Class)
Note: Instructor will frame the problem statement for writing stored procedure and
Function in line with above statement.
Course Objective:

Implement PL/SQL Code block for given requirements

Course Outcome:

C306.4 Implement PL/SQL Code block for given requirements

Software Required: - Mysql

Theory: -
Stored Procedures : 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 anda 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 procedure is similar to
an anonymous PL/SQL Block but it is named for repeated usage.
Procedures: Passing Parameters
We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters
A procedure may or may not return any
value.General Syntax to create a
procedure is:
CREATE [OR REPLACE] PROCEDURE proc_name [list of
parameters]IS
Declaration
sectionBEGIN

37
E xecut ion
Ja ih in d College of Engineering,Kuran
section

38
EXCEPTION
Exception
sectionEND;
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.

Jaihind College of Engineering,Kuran

39
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.
Procedures: Example
The below example creates a procedure ‘employer_details’ which gives the details of the
employee. 1> CREATE OR REPLACE PROCEDURE employer_details
2> IS
3> CURSOR emp_cur IS
4> SELECT first_name, last_name, salary
FROM emp_tbl;5> emp_rec emp_cur%rowtype;
6> BEGIN
7> FOR emp_rec in
sales_cur8> LOOP
9> dbms_output.put_line(emp_cur.first_name || ' '
||emp_cur.last_name10>|| ' '
||emp_cur.salary); 11> END LOOP;
12>END;
13>
There are two ways to execute a procedure.
1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;
2) Within another procedure – simply use the procedure
name. procedure_name;
PL/SQL Functions
A function is a named PL/SQL Block which is similar to a procedure. The major difference between
a procedureand a function is, a function must always return a value, but a procedure may or may
not return a value.
General Syntax to create a function is
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section

BEGIN
VNCOE BOTA

40
Return
return_variable;

VNCOE BOTA

41
DBMS ThirdYear Computer

EXCEPTION
exception
section Return
return_variable;
END;

1) Return Type: The header section defines the return type of the function. The return
datatype can be anyof the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype
defined in theheader section.
For example, let’s create a frunction called ''employer_details_func' similar to the one created
in stored proc1> CREATE OR REPLACE FUNCTION employer_details_func
2> RETURN VARCHAR(20);
3> IS
5> emp_name VARCHAR(20);
6> BEGIN
7> SELECT first_name INTO
emp_name 8> FROM emp_tbl WHERE
empID = '100';9> RETURN
emp_name;
10> END;
In the example we are retrieving the ‘first_name’ of employee with empID 100 to variable
‘emp_name’. The return type of the function is VARCHAR which is declared in line no 2.
The function returns the 'emp_name' which is of type VARCHAR as the return value in line no
9.A function can be executed in the following ways.
1) Since a function returns a value we can assign
it to a variable.employee_name :=
employer_details_func;
If ‘employee_name’ is of datatype varchar we can store the name of the employee by assigning the
return type ofthe function to it.
2) As a part of a SELECT statement
SELECT employer_details_func FROM dual;
3) In a PL/SQL Statements like,
VNCOE BOTA

42
DBMS ThirdYear Computer

dbms_output.put_line(employer_details_func);
This line displays the value returned by the function.

Conclusion:

Students are able to PL/SQL Stored Procedure and Stored Function

Activity to be Submitted by Students

1. Implement Stored Procedure to Check if a given a year is a leap year. The condition
is:- year should be (divisible by 4 and not divisible by 100) or (divisible by 4 and divisible by 400.)
Display the output on the screen using dbms_output.put_line. The year should be input by the user.

2. Implement Stored Procedure or Function to read in a number and print it out digit by digit, as a series
of words. For example, the number 523 would be printed as "five two three". Use decode function within
a for loop. Display the
results on the screen using dbms_output.put_line.

VNCOE BOTA

43
DBMS ThirdYear Computer
Assignment No .6

Title of Assignment: Cursors :( All types: Implicit, Explicit, Cursor FOR Loop, Parameterized Cursor)
Write a PL/SQL block of code using parameterized Cursor that will merge the data available in the
newly created table N_Roll Call 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.
Note: Instructor will frame the problem statement for writing PL/SQL block using all types of Cursors
in line with above statement

Course Objective:
Implement PL/SQL Code block for given requirements

Course Outcome:

C306.4 Implement PL/SQL Code block for given requirements

Software Required: - Mysql

Theory: -
PL/SQL
Cursor

Summary: in this tutorial, we will introduce you to PL/SQL cursor. You will learn step by step how to use
a cursor to loop through a set of rows and process each row individually.
Introducing to PL/SQL Cursor
When you work with Oracle database, you work with a complete set of rows returned from an SQL
SELECT statement. However the application in some cases cannot work effectively with the entire result
set, therefore, the database server needs to provide a mechanism for the application to work with one
row or a subset of the result set at a time. As the result, Oracle created PL/SQL cursor to provide these
extensions.
A PL/SQL cursor is a pointer that points to the result set of an SQL query against
database tables. Working with PL/SQL Cursor
The following picture describes steps that you need to follow when you work with a
PL/SQL cursor:

PL/SQL Cursor
Declaring PL/SQL Cursor
DBMS ThirdYear Computer
To use PL/SQL cursor, first you must declare it in the declaration section of PL/SQL block or in a
package as fo lloJwasi :h ind College of Engineering,Kuran

cur3so8r_nam CURSOR
DBMS ThirdYear Computer
 First, you declare the name of the cursor after the keyword. The name of
the cursor can have up to 30 characters in length and follows the naming rules of identifiers in
PL/SQL. It is
important to note that cursor’s name is not a variable so you cannot use it as a variable such as
assigning it to other cursor or using it in an expression. The parameter1,parameter2… are
optional elements in the cursor declaration. These parameters allow you to pass arguments
RETURN
into the cursor. The
return_specificati is also an optional part.

VNCOE BOTA

39
DBMS ThirdYear Computer
 Second, you specify a valid SQL statement that returns a result set where the cursor points to.
 Third, you can indicate a list of columns that you want to update after the FOR UPDATE OF. This
part is optional so you can omit it in the CURSOR declaration.

PL/SQL Cursor Attributes


These are the main attributes of a PL/SQL cursor and their descriptions.

Attribute Description

cursor_name%FOUND returns TRUE if record was fetched successfully by cursor cursor_name

cursor_name%NOTFOUND returns TRUE if record was not fetched successfully by cursor


cursor_name
cursor_name%ROWCOUNT returns the number of records fetched from the cursor cursor_name at
the time we test %ROWCOUNT attribute

cursor_name%ISOPEN returns TRUE if the cursor cursor_name is open

Explicit Cursors

An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row. We can provide a suitable name for the cursor.
General Syntax for creating a cursor is as given below:

CURSOR cursor_name IS select_statement;

 cursor_name – A suitable name for the cursor.


 select_statement – A select query which returns multiple rows.
 General Syntax to open a cursor is:
 OPEN cursor_name;
 General Syntax to fetch records from a cursor is:
 FETCH cursor_name INTO record_name;
 OR
FETCH cursor_name INTO variable_list;

 General Syntax to close a cursor is:


 CLOSE cursor_name;
VNCOE BOTA

40
DBMS ThirdYear Computer
 When a cursor is opened, the first row becomes the current row. When the data is fetched it is

copied to the record or variables and the logical pointer moves to the next row and it becomes
the current row. On every fetch statement, the pointer moves to the next row. If you want to
fetch after the last row, the program will throw an error. When there is more than one row in a
cursor we can use loops along with explicit cursor attributes to fetch all the records.
FOR LOOP
CursorSyntax
The syntax for the CURSOR FOR LOOP in Oracle/PLSQL is:
FOR record_index
in
cursor_nameLOOP
{...statements...
}END LOOP;
Parameters or Arguments
record_index:The index of the
record.
cursor_name:The name of the cursor that you wish to fetch records from.
statements:The statements of code to execute each pass through the CURSOR FOR LOOP.
Parameterized cursor:
PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to
query. PL/SQL Parameterized cursor define only datatype of parameter and not need
to define its length.Default values is assigned to the Cursor parameters. and scope
of the parameters are locally.
Parameterized cursors are also saying static cursors that can passed parameter value when cursor are
opened.Following example introduce the parameterized cursor. following emp_information table,
EMP_NO EMP_NAME

1 Forbs ross
2 marks jems

3 Saulin

4 Zenia Sroll

Example Code

Cursor display employee information from emp_information table whose emp_no four (4).
Jaciuhrisnodr cC
(no
ollneug
mebeo
r)f iE
s sneg
leicnt e*efrroinmge,m
where
emp_no = no;
41
DBMS ThirdYear Computer
DECLARE

Jaciuhrisnodr cC
(no
ollneug
mebeo
r)f iE
s sneg
leicnt e*efrroinmge,m
where
emp_no = no;
42
DBMS ThirdYear Computer
tmp
emp_information%rowtype; BEGIN
OPEN c(4);

VNCOE BOTA

43
DBMS ThirdYear Computer

FOR tmp IN c(4) LOOP


dbms_output.put_line('EMP_No:
'||tmp.emp_no);
dbms_output.put_line('EMP_Name:
'||tmp.emp_name);END Loop;
CLOSE
c;END;
/
SQL>@parameter_cursor_demo
EMP_No: 4
EMP_Name: Zenia

Conclusion: We have implemented all types of Cursors successfully.

Activity to be Submitted by Students

Write PL/SQL code to display Employee details using Explicit

Cursors Write PL/SQL code in Cursor to display employee

names and salary.

VNCOE BOTA

44
DBMS ThirdYear Computer
Assignment No .7

Title of Assignment: Database Trigger (All Types: Row level and Statement level triggers, Before and
AfterTriggers).
Write a database trigger on Library table. The System should keep track of the records that are being
updated or deleted. The old value of updated or deleted records should be added in Library_Audit table.
Note: Instructor will Frame the problem statement for writing PL/SQLblock for all types of Triggers in
line with above statement.
Course Objective:

Implement PL/SQL Code block for given requirements

Course Outcome:

C306.4 Implement PL/SQL Code block for given requirements

Software Required: - Mysql

PL/SQL Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.Trigger is
stored intodatabase and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some
event occurs.Triggers are written to be executed in response to any of the following
events.
o A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
o A database definition (DDL) statement (CREATE, ALTER, or DROP).
o A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated. Advantages of Triggers
These are the following advantages of Triggers:
o Trigger generates some derived column values automatically
o Enforces referential integrity
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
o Preventing invalid
transactions Creating a trigger:
Syntax for creating trigger:
1. CREATE [OR REPLACE ] TRIGGER trigger_name
2.
Ja{iB
hEinFdOR
CEol|lA
egFTER | INSTEAD OF }
e of Engineering,Kuran
45
DBMS ThirdYear Computer
3. {INSERT [OR] | UPDATE [OR] | DELETE}

46
DBMS ThirdYear Computer
4. [OF col_name]

Jaihind College of Engineering,Kuran

47
DBMS ThirdYear Computer
5. ON table_name
6. [REFERENCING OLD AS o NEW AS n]
7. [FOR EACH ROW]
8. WHEN (condition)
9. DECLARE
10. Declaration-statements
11. BEGIN
12. Executable-statements
13. EXCEPTION
14. Exception-handling-statements
15. END;
Here,
o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with
the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The
INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various
DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each
row being affected. Otherwise the trigger will execute just once when the SQL statement is executed,
which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would fire. This
clause is valid only for row level triggers.
o he price of a product changes constantly. It is important to maintain the history of the
prices of the products.
o We can create a trigger to update the 'product_price_history' table when the price of the
product is updated in the 'product' table.
1) Create the 'product' table and 'product_price_history' table
CREATE TABLE
product_price_history (product_id
number(5),

48
DBMS ThirdYear Computer
supplier_name varchar2(32),
unit_price number(7,2) );

CREATE TABLE product


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

2) Create the price_history_trigger and execute it.


CREATE or REPLACE TRIGGER
price_history_trigger BEFORE UPDATE OF
unit_price
ON product

FOR EACH ROW


BEGIN

INSERT INTO
product_price_history VALUES

(:old.product_id,

:old.product_name,

:old.supplier_name,

:old.unit_price)
;
END;

/
3) Lets update the price of a product.
UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100

Once the above update query is executed, the trigger fires and updates the 'product_price_history' table.
4) If you ROLLBACK the transaction before committing to the database, the data inserted to the
,it is triggered.

49
DBMS ThirdYear Computer
table is also rolled back.
Types of PL/SQL Triggers

,it is triggered.

50
DBMS ThirdYear Computer
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement
executed. PL/SQL Trigger Execution Hierarchy

51
DBMS ThirdYear Computer
The following hierarchy is followed when a trigger is fired.
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row affected.
3) Then AFTER row level trigger fires once for each affected row. This events will alternates between
BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.
For Example: Let's create a table 'product_check' which we can use to store messages when triggers
are fired.
CREATE TABLE
product (Message
varchar2(50),
Current_Date
number(32)

);

Let's create a BEFORE and AFTER statement and row level triggers for the product table.
1) BEFORE UPDATE, Statement Level: This trigger will insert a record into the table 'product_check'
before a sql update statement is executed, at the statement level.
CREATE or REPLACE TRIGGER Before_Update_Stat_product
BEFORE

UPDATE ON product
Begin

INSERT INTO product_check


Values('Before update,
statement level',sysdate);END;

2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table 'product_check' before
each row is updated.
CREATE or REPLACE TRIGGER
Before_Upddate_Row_product BEFORE

52
DBMS ThirdYear Computer
UPDATE ON
product FOR EACH
ROW BEGIN

53
DBMS ThirdYear Computer
INSERT INTO product_check
Values('Before update row
level',sysdate); END;

54
DBMS ThirdYear Computer
3) AFTER UPDATE, Statement Level: This trigger will insert a record into the table 'product_check'
after a sql update statement is executed, at the statement level.
CREATE or REPLACE TRIGGER
After_Update_Stat_product AFTER

UPDATE ON
product BEGIN

INSERT INTO product_check


Values('After update, statement
level', sysdate);End;

/
4) AFTER UPDATE, Row Level: This trigger will insert a record into the table 'product_check' after
each row is updated.
CREATE or REPLACE TRIGGER
After_Update_Row_product AFTER

insert On
product FOR
EACH ROW
BEGIN

INSERT INTO product_check


Values('After update, Row
level',sysdate); END;

/
Now lets execute a update statement on table product.
UPDATE PRODUCT SET unit_price =
800 WHERE product_id in (100,101);

Lets check the data in 'product_check' table to see the order in which the trigger is fired.
SELECT * FROM product_check;

Output:
Mesage Current_Date
Before update, statement 26-Nov-
55
DBMS ThirdYear Computer

Jaihind College of Engineering,Kuran

Before update, statement 26-Nov-


56
DBMS ThirdYear Computer
Before update, row level 26-Nov-2008
After update, Row level 26-Nov-2008
Before update, row level 26-Nov-2008

57
DBMS ThirdYear Computer

After update, Row level 26-Nov-


2008After update, statement level 26-Nov-
2008

Conclusion: We have implemented all types of Triggers successfully.

Activity to be Submitted by Students

1. Write pl/sql code in Trigger not to accept the existing Empno (Unique no)
2. Write pl/sql code using Trigger to salary with more than old salary

58
Assignment No .8

Title of Assignment: Database Connectivity:


Write a program to implement MySQL/Oracle database connectivity with any front
endlanguage to implement Database navigation operations (add, delete, edit etc.)

Course Objective:
Implement PL/SQL Code block for given requirements

Course Outcome:

C306.6
Design and develop application considering actual requirements and using database concepts

Software Required: - Mysql/eclipse/ wampserver/php/oracle

Why use JDBC


Before JDBC, ODBC API was the database API to connect and execute query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured).
That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java
language).
JDBC Driver
1. JDBC Drivers
1. JDBC-ODBC bridge driver
2. Native-API driver
3. Network Protocol driver
4. Thin driver
JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBCmethod calls into the ODBC function calls. This is now discouraged because of thin
driver.
Advantages:
o easy to use.
o can be easily connected to any
database. Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function calls.
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into
o The ODBC driver needs to be installed on the client machine.
2) Nativ
Jea-iAhPinI ddrC
ivo
erllege of Engineering,Kuran

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into
native callsof the database API. It is not written entirely in
java. Advantage:
o performance upgraded than JDBC-ODBC
bridge driver.Disadvantage:
o The Native driver needs to be installed on the each client machine.

61
o The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to
be donein the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server
side. Disadvantage:
o Drivers depends on the
Database. 5 Steps to connect to the
database in javaThey are as follows:
o Register the driver class
o Creating connection
o Creating statement
o Executing queries
o Closing connection
1)Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Syntax of forName() method
1. public static void forName(String className)throws
ClassNotFoundExceptionExample to register the OracleDriver
class
1. Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with

VNCOE BOTA

62
the database.Syntax of getConnection() method

VNCOE BOTA

63
3) public static Connection getConnection(String url)throws SQLException
4) public static Connection getConnection(String url,String name,String password)
throws SQLExceptionExample to establish connection with the Oracle database
5) Connection con=DriverManager.getConnection(
6) "jdbc:oracle:thin:@localhost:1521:xe","system","password");
7) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsibleto execute queries with the database.
Syntax of createStatement() method
public Statement
createStatement()throws
SQLExceptionExample to create the statement
object Statement stmt=con.createStatement();
8) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database. This
method returns theobject of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws
SQLExceptionExample to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){ System.out.println(rs.getInt(1)+"
"+rs.getString(2));
}
9) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection. Syntax of close() method
public void close()throws
SQLExceptionExample to
close connection con.close();
import
java.sql.*;
class
OracleCon
{
public static void main(String
args[]){try{
Class.forName("oracle.jdbc.driver.OracleDriver");

K
muerm
apn");

64
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");Statement stmt=con.createStatement();

K
muerm
apn");

65
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

VNCOE BOTA

66
con.close();
}catch(Exception e){ System.out.println(e);} } }

PHP Connectivity
PHP will require that mysqli is enabled (it is on most PHP set ups).
$db =
mysqli_connect('localhost','username','password','database_na
me')or die('Error connecting to MySQL server.');
The variable $db is created and assigned as the connection string, it will be used in future steps. If
there is a failure then anerror message will be displayed on the page. If it is successful you will see
PHP connect to MySQL.
Performing a database query
The mysql query is actually performed in the body of the html page, so additional php opening and
closing tags will be required. For the query we are going to specify a read of all fields from a given
table. The $query variable selects all rows in the table. You just need to use your table name.
<?php
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying
database.');
Again the returned page in the browser should be blank and error free, if you do receive the error –
‘Error queryingdatabase..’ check the table name is correct.
<?php
//Step1
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying
database.');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);

VNCOE BOTA

67
DBMS ThirdYear Computer

while ($row = mysqli_fetch_array($result)) {


echo $row['first_name'] . ' ' . $row['last_name'] . ': ' . $row['email'] . ' ' . $row['city'] .'<br />';}?>
</body>
</html>
Closing off the connection
Closing the connection will require another set off opening and closing php tags after the closing html
tag.
<?php
//Step1
$db =
mysqli_connect('localhost','root','root','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
//Step2
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying
database.');
//Step3
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while ($row = mysqli_fetch_array($result)) {
echo $row['first_name'] . ' ' . $row['last_name'] . ': ' . $row['email'] . ' ' . $row['city'] .'<br />';}
//Step 4
mysqli_close(
$db);
?>
</body>
</html>

Conclusion: We have implemented database connectivity

VNCOE BOTA

68
DBMS ThirdYear Computer
Activity to be Submitted by Students

VNCOE BOTA

69
DBMS ThirdYear Computer

1. Login page in PHP

VNCOE BOTA

70
Assignment No

Title of Assignment: MongoDB Queries:


Design and Develop MongoDB Queries using CRUD operations. (Use CRUD operations,SAVE method, logical
operators etc.).

Course Objective:
To acquire the skills to use a powerful, flexible, and scalable general-purpose databases to handle Big Data

Course Outcome:

Implement NoSQL queries using MongoDB

Software Required: - Mongodb

The use Command


use
DATABASE_NAME

MongoDB use DATABASE_NAME is used to create database. The command will create a new database,
if it doesn't existotherwise it will return the existing database.Syntax:
Example:If you want to create a database with name <mydb>, then use DATABASE statement would be as follows:

>use mydb
To check your currently selected database use the command db
>db;
The dropData
MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax: Basic syntax of dropDatabase() command is as follows:

db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete
default 'test' database
MongoDB Create Collection The createCollection() Method:
MongoDB db.createCollection(name, options) is used to create
collection. db.createCollection(name, options)

Syntax:
In the command, name is name of collection to be created. Options is a document and used to specify
configuration of collection
The drop() Method
MongoDB's db.collection.drop() is used to drop a collection from the database.
db.COLLECTION_NAME.drop()

71
Assignment No
Syntax:

72
To insert data into MongoDB collection, you need to use MongoDB's insert() or
Syntax

Basic syntax of insert() command is as follows:


>db.COLLECTION_NAME.insert(document)
Example
>db.stud1.insert({name:’abc’,age:20})

Query Documents (Find)

VNCOE BOTA

73
In MongoDB, the db.collection.find() method retrieves documents from a collection. The
db.collection.find() method returns a cursor to the retrieved documents. The db.collection.findOne()
method also performs a read operation to return a single document. Internally, the
db.collection.findOne() method is the db.collection.find() method with a limit of
1. Select All Documents in a Collection
An empty query document ({}) selects all documents in the collection:
db.inventory.find( {} )
Not specifying a query document to the find() is equivalent to specifying an empty query document.
Therefore thefollowing operation is equivalent to the previous operation:
db.inventory.find()
Specify Equality Condition
To specify equality condition, use the query document { <field>: <value> } to select all documents that
contain the <field> with the specified <value>. The following example retrieves from the inventory
collection all documents where the type field has the value snacks:
db.inventory.find( { type: "snacks" } )
Specify Conditions Using Query Operators
A query document can use the query operators to specify conditions in a MongoDB query.
The following example selects all documents in the inventory collection where the value of the type
field is either 'food' or'snacks':
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )
Although you can express this query using the $or operator, use the $in operator rather than the
$or operator whenperforming equality checks on the same field.
Comparison Operators and Logical Operators : For comparison of different BSON type values, see the specified
BSON comparison order.

Comparison
OperatorName
Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$in Matches any of the values specified in an array.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$nin Matches none of the values specified in an array.
Logical
Operators
Name
iN
ng
D,documents that match the conditions of both clauses.

74
Description

iN
ng
D,documents that match the conditions of both clauses.

75
$not Inverts the effect of a query expression and returns documents that do not match the query
expression.

VNCOE BOTA

76
DBMS ThirdYear Computer

$nor Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
$or Joins query clauses with a logical OR returns all documents that match the conditions of either
clause.
SAVE METHOD
The save() method has the following form:
db.collection.save( <document>, { writeConcern:
<document> })The products collection contains
the following document:
{ "_id" : 100, "item" : "water", "qty" : 30 }
The save() method performs an update with upsert:true since the document contains an
_id field:db.products.save( { _id : 100, item : "juice" } )
MongoDB Logical Query Operator - $and & $not
Logical Operator - $and
The MongoDB $and operator performs a logical AND operation on an array of two or more
expressions and retrieves the documents which satisfy all the expressions in the array. The $and
operator uses short-circuit evaluation. If the first expression (e.g. <expression1>) evaluates to false,
MongoDB will not evaluate the remaining expressions.
Syntax:
{ $and: [ { <exp1> }, { <exp2> } , ... , { <expN> } ] }
Our database name is 'myinfo' and our collection name is 'student'. Here,
is the collection bellow.Example of MongoDB Logical Operator - $and
If we want to select all documents from the collection "student" which satisfying the condition -
1. sex of student is Female and
2. class of the student is VI and
3. grd_point of the student is greater than equal to 31 the following mongodb command can be used :
>db.student.find({$and:[{"sex":"Male"},{"grd_point":{ $gte: 31 }},{"class":"VI"}]}).pretty();
Logical Operator - $not
The MongoDB $not operator performs a logical NOT operation on the given expression and fetches
selected documentsthat do not match the expression and the document that do not contain the field
as well, specified in the expression.
Syntax:
{ field: { $not: { <expression> } } }
Example of MongoDB Logical Operator - $not
If we want to select all documents from the collection "student" which satisfying the condition -age
of the student is at least 12 the following mongodb command can be used :
>db.student.find( {"age": { $not: {$lt :

VNCOE BOTA

77
DBMS ThirdYear Computer

12}}}).pretty();The following mongodb


command can be used :
>db.student.find( {"sex": { $not: /^M.*/}}).pretty();

Conclusion: We have implemented CRUD operations using Mongodb

Activity to be Submitted by Students

1. Collection “orderinfo“ which contains the documents given as below(Perform on Mongo Terminal)
{
cust_id:123
cust_name:”abc”,
status:”A”,
price:250
}
i. find the average price for each customers having status 'A'
ii. Display the status of the customers whose amount/price lie between 100 and 1000
iii. Display the customers information without “_id” .
iv. create a simple index on onderinfo collection and fire the queries.

2. Collection “movies“ which contains the documents given as below(Perform on Mongo Terminal)

{
name: “Movie1”,
type: “action”,
budget:100000
0 producer:{

name:
“producer1”,
address:”PUNE”
}
}

i. Find the name of the movie having budget greater than 1,00,000.
ii. Find the name of producer who lives in Pune
iii. Update the type of movie “action” to “horror”
iv. Find all the documents produced by name “producer1” with their address

VNCOE BOTA

78
Assignment No .10

Title of Assignment: MongoDB – Aggregation and Indexing:


Design and Develop MongoDB Queries using aggregation and indexing with suitable exampleusing
MongoDB.
Course Objective:
To acquire the skills to use a powerful, flexible, and scalable general-purpose databases to handle Big
Data

Course Outcome:

Implement NoSQL queries using MongoDB

Software Required: - Mongodb

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 requires the mongod 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.
The ensureIndex() Method
To create an index you need to use ensureIndex() method of mongodb.
SYNTAX:
Basic syntax of ensureIndex() method is as follows()

>db.COLLECTION_NAME.ensureIndex({KEY:1})

Here key is the name of filed on which you want to create index and 1 is for ascending order. To
create index in descending order you need to use -1.
EXAMPLE

>db.mycol.ensureIndex({"title":1})

In ensureIndex() method you can pass multiple fields, to create index on multiple fields.

>db.mycol.ensureIndex({"title":1,"description":-1})
Drop Index :

>db.mycol.dropIndex({"title":1,"description":-1})
J a i h i nd C o l leg e o f E n g i n e e r i n g , Ku r a n
the g rouped data to return a s in g l e re s u l t. I n sq l c ount(*) and with group by is an equivalent of
MongoDB
AGGREGATION :Aggregations operations process data records and return computed results.
operations on

J a i h i nd C o l leg e o f E n g i n e e r i n g , Ku r a n
the g rouped data to return a s in g l e re s u l t. I n sq l c ount(*) and with group by is an equivalent of
MongoDB
aggregation The aggregate() Method For the aggregation in mongodb you should use
method.SYNTAX: Basic syntax of aggregate() method is as follows

81
Now from the above collection if you want to display a list that how many

{_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},
written by each user then you will use aggregate() method as shown below:

> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])


{"result" : [{"_id" : "tutorials point", "num_tutorial" : 2},
{"_id" : "tutorials point", "num_tutorial" : 1}],"ok" : 1}

SQL equivalent query for the above use case will be select by_user, count(*) from mycol group by
by_user. In the above example we have grouped documents by field by_user and on each occurance
of by_user previous value of sum is incremented. There is a list available aggregation expression.

Express Description Example


i
on
$sum Sums up the defined from al db.mycol.aggregate([{$group : {_id :
value documents in the "$by_user" num_tutorial : {$sum : "$likes"}}}])
collection.
$avg Calculates the average of all given db.mycol.aggregate([{$group : {_id :
values from all documents in the "$by_user" num_tutorial : {$avg : "$likes"}}}])
collection.
$min Gets the minimum of the db.mycol.aggregate([{$gro : {_id :
corresponding all up "$by_user", num_tutorial : {$min :
values from "$likes"}}}])
documents in the collection.

82
Now from the above collection if you want to display a list that how many
$max Gets the maximum of th db.mycol.aggregate([{$gro : {_id :
corresponding e up "$by_user",num_tutorial : {$max :
values from documents in all "$likes"}}}])
the collection.

83
DBMS ThirdYear Computer

$push Inserts the value to an array in the db.mycol.aggregate([{$group : {_id :


resulting
"$by_user", url : {$push: "$url"}}}])
document.
$addTo Inserts the value to an array in the
S et resulting document but does not create db.mycol.aggregate([{$group : {_id :
duplicates. "$by_user", url : {$addToSet : "$url"}}}])
$first Gets the first document from the source db.mycol.aggregate([{$group : {_id :
documents according to the grouping. "$by_user", first_url : {$first : "$url"}}}])

Gets the last document from the source db.mycol.aggregate([{$group : {_id :


documents according to the grouping. "$by_user", last_url : {$last : "$url"}}}])
$last
Pipeline Concept
In UNIX command shell pipeline means the possibility to execute an operation on some input and use
the output as the input for the next command and so on. MongoDB also support same concept in
aggregation framework. There is a set of possible stages and each of those is taken a set of
documents as an input and is producing a resulting set of documents (or the final resulting JSON
document at the end of the pipeline). This can then in turn again be used for the next stage an so on.
Possible stages in aggregation framework are following:
 $project: Used to select some specific fields from a collection.
 $match: This is a filtering operation and thus this can reduce the amount of documents that
are given as input to the next stage.
 $group: This does the actual aggregation as discussed above.
 $sort: Sorts the documents.
 $skip: With this it is possible to skip forward in the list of documents for a given amount of
documents.
 $limit: This limits the amount of documents to look at by the given number starting from the
current position.s
 $unwind: This is used to unwind document that are using arrays. when using an array the
data is kind of pre-joined and this operation will be undone with this to have individual documents
again. Thus with this stage we will increase the amount of documents for the next stage.

84
DBMS ThirdYear Computer

Conclusion: We have implemented aggregation and indexing using Mongodb

Activity to be Submitted by Students

Perform aggregation and Indexing using mongodb on below database


1. Create a database department
2. Create a collection as teacher with fields as name , department ,experience and salary
3. Display the department wise average salary.
4. Display the no. Of employees working in each department.
5. Display the department wise minimum salary.
6. Apply index and drop index

85
Assignment No .11

Title of Assignment: MongoDB – Map-reduces operations:


Implement Map reduces operation with suitable example using MongoDB.
Course Objective:
To acquire the skills to use a powerful, flexible, and scalable general-purpose databases to handle Big Data

Course Outcome:

Implement NoSQL queries using MongoDB

Software Required: - Mongodb

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. In simple terms, the mapReduce command takes 2
primary inputs, the mapper function and the reducer function .
Working of Mapper and Reducer Function :
MapReduce is a two-step approach to data processing. First you map, and then you reduce. The
mapping step transforms the inputted documents and emits a key=>value pair (the key and/or value
can be complex). Then, key/value pairs are grouped by key, such that values for the same key end up
in an array. The reduce gets a key and the array of values emitted for that key, and produces the final
result. The map and reduce functions are written in JavaScript. A Mapper will start off by reading a
collection of data and building a Map with only the required fields we wish to process and group
them into one array based on the key. And then this key value pair is fed into a Reducer, which will
process the values.
MapReduce Command:
syntax of the basic mapReduce command:
db.collection.mapReduce(function() {emit(key,value);}, //map
function function(key,values) {return reduceFunction}, //reduce
function
{out: collection, query: document, sort: document, limit: number})

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. MapReduce
Command:
86
syntax of the basic mapReduce command:
db.co lle ction.map R educe(f unctio n()
Ja i h i n d C oll e g e o f E n g in ee{rienmgit,(Kku
ey,value);},
ran //map function
function(key,values) {return reduceFunction}, //reduce function

87
{out: collection, query: document, sort: document, limit: number}) 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.

88
DBMS ThirdYear Computer

In the above syntax:


map is a javascript function that maps a value with a key and emits a key-value pair
reduce is a javascript 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
Map Reduce Example
The below example is to retrieve the sum of total values related to particular key.
1. Insert data in mapCollection.

db.mapc.insert({key:”a”, value:2})
db.mapc.insert({key:”a”, value:4})

Conclusion: We have implemented Map reduce using Mongodb Successfully

Activity to be Submitted by Students

Collection “city “ which contains the documents given as below(Perform on Mongo Terminal)

89
DBMS ThirdYear Computer

city:”pune”,

type:”urban”,

state:”MH”,

population:”5600000”

-using mapreduce, find statewise population

-using mapreduce, find citywise population

-using mapreduce, find typewise population.

90
Assignment No .12

Title of Assignment: Database Connectivity:


Write a program to implement MySQL/Oracle database connectivity with any front
endlanguage to implement Database navigation operations (add, delete, edit etc.)

Course Objective:
Implement PL/SQL Code block for given requirements

Course Outcome:

C306.6
Design and develop application considering actual requirements and using database concepts

Software required: - Mongodb/eclipse/ wampserver/php

Mongodb
Connectivity
Mongo
connection
Connect to MongoDB server. For MongoDB version >= 2.10.0, uses MongoClient.
// Old version, uses Mongo
Mongo mongo = new Mongo("localhost", 27017);
// Since 2.10.0, uses MongoClient
MongoClient mongo = new
MongoClient( "localhost" , 27017 );If MongoDB in
secure mode, authentication is required.
MongoClient mongoClient = new
MongoClient();DB db =
mongoClient.getDB("database
name");
boolean auth = db.authenticate("username", "password".toCharArray());
Mongo Database
Get database. If the database doesn’t exist, MongoDB will
create it for you.DB db = mongo.getDB("database name");
Display all collections from selected
database.DB db =
mongo.getDB("testdb");
Save example
Save a document (data) into a collection (table) named
BasicJDaBihOin
bjd
ecC
t doolcle
umgeento=f

91
“user”.DBCollection table = db.getCollection("user");

BasicJDaBihOin
bjd
ecC
t doolcle
umgeento=f

92
BasicDBObject();document.put("name",
"mkyong"); document.put("age", 30);
document.put("createdDate", new Date());
table.insert(document);
Update example
Update a document where
“name=mkyong”. DBCollection table
= db.getCollection("user");
BasicDBObject query = new
BasicDBObject(); query.put("name",
"mkyong");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "mkyong-updated");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);

93
DBMS Lab ThirdYear Computer Engineering

table.update(query, updateObj);
Find example
Find document where “name=mkyong”, and display it with
DBCursorDBCollection table = db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
DBCursor cursor =
table.find(searchQuery);while
(cursor.hasNext()) {
System.out.println(cursor.next());
}
Delete example
Find document where “name=mkyong”, and delete it.DBCollection table =
db.getCollection("user"); BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong"); table.remove(searchQuery);

Conclusion: We have implemented database connectivity

Activity to be Submitted by Students

1. CRUD operation using Mongodb and JDBC connectivity

VNCOE BOTA

94

You might also like