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

Lab Manual DBMS (2)

The document is a laboratory manual for the Database Management System Lab at Dr. D. Y. Patil School of Engineering, outlining various assignments and projects related to SQL, PL/SQL, and NoSQL databases like MongoDB. It includes detailed instructions for creating SQL queries, PL/SQL blocks, and database triggers, as well as guidelines for a mini project involving database application development. The manual serves as a comprehensive guide for students to learn and implement database concepts and programming languages relevant to their coursework.

Uploaded by

shivani chougule
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lab Manual DBMS (2)

The document is a laboratory manual for the Database Management System Lab at Dr. D. Y. Patil School of Engineering, outlining various assignments and projects related to SQL, PL/SQL, and NoSQL databases like MongoDB. It includes detailed instructions for creating SQL queries, PL/SQL blocks, and database triggers, as well as guidelines for a mini project involving database application development. The manual serves as a comprehensive guide for students to learn and implement database concepts and programming languages relevant to their coursework.

Uploaded by

shivani chougule
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

Dr. D. Y.

Patil Technical Campus

Dr. D. Y. Patil School of Engineering


Dr. D. Y. Patil Knowledge City, Charholi (Bk), Lohegaon, Pune – 412 105

Department of Computer Engineering

Database Management System Lab


(T. E. Computer) 2015 Course

LABORATORY MANUAL
(Version 2, w. e. f. Dec 2015)

Prepared By Approved By
Ms. Navale Ashwini M. Prof. Soumitra Das
Ms.Vandana Chavan (H. O. D.)
(Asst Professor)
2

Group A- Database Programming Languages – SQL, PL/SQL

Study of Open Source Relational Databases : MySQL


1

Design and Develop SQL DDL statements which demonstrate the use of SQL
2 objects such as Table, View, Index, Sequence, Synonym

Design at least 10 SQL queries for suitable database application using SQL
3 DML statements: Insert, Select, Update, Delete with operators, functions, and
set operator.
Design at least 10 SQL queries for suitable database application using SQL
4 DML statements: all types of Join, Sub-Query and View.

Unnamed PL/SQL code block: Use of Control structure and Exception


5 handling is mandatory. Write a PL/SQL block of code for the following
requirements:-
Schema:
1. Borrower(Rollin, Name, DateofIssue, NameofBook, Status)
2. Fine(Roll_no,Date,Amt)

then fine amount will be Rs 5per day.


er day & for days less than
30, Rs. 5 per day.

Frame the problem statement for writing PL/SQL block inline with above
statement.
Cursors: (All types: Implicit, Explicit, Cursor FOR Loop, Parameterized
6 Cursor) Write a PL/SQL block of code using parameterized Cursor, that will
merge the data available in the newly created table N_RollCall with the data
available in the table O_RollCall. If the data in the first table already exist in
the second table then that data should be skipped.
Frame the separate problem statement for writing PL/SQL block to implement
all typeof Cursors inline with above statement. The problem statement should
clearly state the requirements.
7 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 marks 899 and 825 category is Higher Second
Class Write a PL/SQL block for using procedure created with above
requirement. Stud_Marks(name, total_marks) Result(Roll,Name, Class)

Frame the separate problem statement for writing PL/SQL Stored Procedure
and function, inline with above statement. The problem statement should

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
3

clearly state the requirements.

8 Database Trigger (All Types: Row level and Statement level triggers, Before
and After Triggers). 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.
Frame the problem statement for writing Database Triggers of all types, in-line
with above statement. The problem statement should clearly state the
requirements.

Group B Large Scale Databases

1 Study of Open Source NOSQL Database: MongoDB (Installation, Basic


CRUD operations, Execution)

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

3 Implement aggregation and indexing with suitable example using MongoDB.

4 Implement Map reduces operation with suitable example using MongoDB.

5 Design and Implement any 5 query using MongoDB

6 Create simple objects and array objects using JSON

7 Encode and Decode JSON Objects using Java/Perl/PHP/Python/Ruby

Group C Mini Project : Database Project Life Cycle

1 Write a program to implement MogoDB database connectivity with PHP/


python/Java Implement Database navigation operations (add, delete, edit etc. )
using ODBC/JDBC.
2 Implement MYSQL/Oracle database connectivity with PHP/ python/Java
Implement Database navigation operations (add, delete, edit,) using
ODBC/JDBC.
3 Using the database concepts covered in Part-I & Part-II & connectivity
concepts covered in Part C, students in group are expected to design and
develop database application with following details:
Requirement Gathering and Scope finalization
Database Analysis and Design:

Normalization
Implementation :

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
4

Testing : Data Validation


Group of students should submit the Project Report which will be consist of
documentation related to different phases of Software Development Life
Cycle: Title of the Project, Abstract, Introduction, scope, Requirements, Data
Modeling features, Data Dictionary, Relational Database Design, Database
Normalization, Graphical User Interface, Source Code, Testing document,
Conclusion. Instructor should maintain progress report of mini project
throughout the semester from project group and assign marks as a part of the
term work

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
5

Index
Sr. Page
Problem Statement / Aim
No. No.
1 A1.Study of Open Source Relational Databases : MySQL 7

A2. Design and Develop SQL DDL statements which demonstrate the use of SQL
2 13
objects such as Table, View, Index, Sequence, Synonym

A3.Design at least 10 SQL queries for suitable database application using SQL DML
3 23
statements: Insert, Select, Update, Delete with operators, functions, and set operator.

A4. Design at least 10 SQL queries for suitable database application using SQL DML
4 38
statements: all types of Join, Sub-Query and View.
A5.Unnamed PL/SQL code block: Use of Control structure and Exception handling is
mandatory. Write a PL/SQL block of code for the following requirements:-
Schema:
1. Borrower(Rollin, Name, DateofIssue, NameofBook, Status)
2. Fine(Roll_no,Date,Amt)

5 44
amount will be Rs 5per day.
of days>30, per day fine will be Rs 50 per day & for days less than 30, Rs. 5 per
day.

Frame the problem statement for writing PL/SQL block inline with above
statement.
A6.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_RollCall with the data available in the table
O_RollCall. If the data in the first table already exist in the second table then that data
6 63
should be skipped.
Frame the separate problem statement for writing PL/SQL block to implement all
types of Cursors inline with above statement. The problem statement should clearly
state the requirements.
A7.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 marks 899 and 825 category is Higher Second Class
7 71
Write a PL/SQL block for using procedure created with above requirement.
Stud_Marks(name, total_marks) Result(Roll,Name, Class)
Frame the separate problem statement for writing PL/SQL Stored Procedure
and function, inline with above statement. The problem statement should clearly
state the requirements.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
6

Sr. Page
Problem Statement / Aim
No. No.
A8.Database Trigger (All Types: Row level and Statement level triggers, Before and
After Triggers). 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
8 deleted records should be added in Library_Audit table. 76
Frame the problem statement for writing Database Triggers of all types, in-line
with above statement. The problem statement should clearly state the
requirements.
B1.Study of Open Source NOSQL Database: MongoDB (Installation, Basic CRUD
9 operations, Execution) 86

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

B3.Implement aggregation and indexing with suitable example using MongoDB.


11 100

12 B4.Implement Map reduces operation with suitable example using MongoDB. 111

B5.Design and Implement any 5 query using MongoDB


13 116

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
7

Assignment No. A1
Title: Study of Open Source Relational Databases: MySQL

Problem Statement / Aim: Upon Completion of this assignment students should able to learn

1. Introduction with MySQL Open Source Database

2. Installation of MySQL on Linux

3. Executing simple SQL Commands using MySQL

3. Introduction with MySQL Datatypes.

Theory:

What is a Database?

A database is a separate application that stores a collection of data. Each database has one or more distinct
APIs for creating, accessing, managing, searching and replicating the data it holds. Other kinds of data
stores can also be used, such as files on the file system or large hash tables in memory, but data fetching
and writing would not be so fast and easy with those type of systems. Nowadays, we use relational
database management systems (RDBMS) to store and manage huge volume of data. This is called
relational database because all the data is stored into different tables and relations are established using
primary keys or other keys known as Foreign Keys. A Relational DataBase Management System
(RDBMS) is a software that:

 Enables you to implement a database with tables, columns and indexes.

 Guarantees the Referential Integrity between rows of various tables.

 Updates the indexes automatically.

 Interprets an SQL Query and combines information from various tables.

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

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
8

subscription.

 Redundancy: Storing data twice, redundantly to make the system faster.

 Primary Key: A primary key is unique. A key value cannot occur twice in one table. With a key, you

can 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.

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.  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.

 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.

Installation of MySQL on Linux

1. Install mysql server on linux using following command

[root@localhost]# yum -y install community –mysql-server

2. Start mysql Server Services

[root@Localhost]# systemctl start mysqld.service

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
9

3. Mysql secure installation (Setting root password)

[root@localhost]# mysql_secure_installation

/usr/bin/mysqladmin -u root password ‘dbms’;

4. Start Mysql

[root@localhost]# mysql -uroot -pdbms;

Verifying MySQL Installation

[root@localhost]# mysqladmin –version

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.

 SHOW TABLE STATUS LIKE tablename\G: Reports details of the MySQL DBMS performance and

statistics.

MySQL Datatypes

Properly defining the fields in a table is important to the overall optimization of your database. You
should use only the type and size of field you really need to use. For example, do not define a field 10
characters wide, if you know you are only going to use 2 characters. These type of fields (or columns) are
also referred to as data types, after the type of data you will be storing in those fields. MySQL uses many
different data types broken into three categories:

 Numeric

 Date and Time

 String Types Let us now discuss them in detail.

Numeric Data Types

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
10

MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a
different database system, these definitions will look familiar to you. The following list shows the
common numeric data types and their descriptions:

 INT – A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from –

2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify
a

width of up to 11 digits.

 TINYINT – A very small integer that can be signed or unsigned. If signed, the allowable range is from

128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.

 SMALLINT – A small integer that can be signed or unsigned. If signed, the allowable range is from –

32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of up to 5

digits.

 MEDIUMINT – A medium-sized integer that can be signed or unsigned. If signed, the allowable range
is

from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can specify a

width of up to 9 digits.

 BIGINT – A large integer that can be signed or unsigned. If signed, the allowable range is from –

9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to

18446744073709551615. You can specify a width of up to 20 digits.

 FLOAT(M,D) – A floating-point number that cannot be unsigned. You can define the display length
(M)

and the number of decimals (D). This is not required and will default to 10,2, where 2 is the number
of

decimals and 10 is the total number of digits (including decimals). Decimal precision can go to 24

places for a FLOAT.

 DOUBLE(M,D) – A double precision floating-point number that cannot be unsigned. You can define
the

display length (M) and the number of decimals (D).This is not required and will default to 16,4, where
4

is the number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym

for DOUBLE.

 DECIMAL(M,D) – An unpacked floating-point number that cannot be unsigned. In the unpacked

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
11

decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of

decimals (D) is required. NUMERIC is a synonym for DECIMAL.

Date and Time Types

The MySQL date and time datatypes are as follows:

 DATE – A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example,

December 30th 1973 would be stored as 1973-12-30.

 DATETIME – A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-

01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th 1973

would be stored as 1973-12-30 15:30:00.

 TIMESTAMP – A timestamp between midnight, January 1st 1970 and sometime in 2037. This looks
like

the previous DATETIME format only, but without the hyphens between numbers; 3:30 in the afternoon

on December 30th 1973 would be stored as 19731230153000 (YYYYMMDDHHMMSS).

 TIME – Stores the time in a HH:MM:SS format.

 YEAR(M) – Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example

YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4, then YEAR

can be 1901 to 2155. The default length is 4.

String Types

Although the numeric and date types are fun, most data you'll store will be in a string format. This list
describes the common string datatypes in MySQL.

 CHAR(M) – A fixed-length string between 1 and 255 characters in length (for example CHAR(5)),

right-padded with spaces to the specified length when stored. Defining a length is not required, but the

default is 1.

 VARCHAR(M) – A variable-length string between 1 and 255 characters in length. For example,

VARCHAR(25). You must define a length when creating a VARCHAR field.

 BLOB or TEXT – A field with a maximum length of 65535 characters. BLOBs are "Binary Large
Objects" and are used to store large amounts of binary data, such as images or other types of files. Fields
defined as TEXT also hold large amounts of data. The difference between the two is that the sorts and
comparisons on the stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields.
You do not specify a length with BLOB or TEXT.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
12

 TINYBLOB or TINYTEXT – A BLOB or TEXT column with a maximum length of 255 characters.
You do not specify a length with TINYBLOB or TINYTEXT.

 MEDIUMBLOB or MEDIUMTEXT – A BLOB or TEXT column with a maximum length of


16777215 characters. You do not specify a length with MEDIUMBLOB or MEDIUMTEXT.

 LONGBLOB or LONGTEXT – A BLOB or TEXT column with a maximum length of 4294967295


characters. You do not specify a length with LONGBLOB or LONGTEXT.

 ENUM – An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a

List of items from which the value must be selected (or it can be NULL). For example, if you wanted

your field to contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C') and only

those values (or NULL) could ever populate that field.

MySQL Transactions

A transaction is a sequential group of database manipulation operations, which is performed as if it were


one single work unit. In other words, a transaction will never be complete unless each individual
operation within the group is successful. If any operation within the transaction fails, the entire
transaction will fail. Practically, you will club many SQL queries into a group and you will execute all of
them together as a part of a transaction.

Properties of Transactions

Transactions have the following four standard properties, usually referred to by the acronym ACID:

 Atomicity: This ensures that all operations within the work unit are completed successfully; otherwise,

the transaction is aborted at the point of failure and previous operations are rolled back to their former

state.

 Consistency: This ensures that the database properly changes states upon a successfully committed

transaction.

 Isolation: This enables transactions to operate independently on and transparent to each other.

 Durability: This ensures that the result or effect of a committed transaction persists in case of a system

failure. In MySQL, the transactions begin with the statement BEGIN WORK and end with either a

COMMIT or a ROLLBACK statement.

The SQL commands between the beginning and ending statements form the bulk of the transaction.
COMMIT and ROLLBACK These two keywords Commit and Rollback are mainly used for MySQL
Transactions.

 When a successful transaction is completed, the COMMIT command should be issued so that the
changes to all involved tables will take effect.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
13

 If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the
transaction to its previous state. You can control the behavior of a transaction by setting session variable
called AUTOCOMMIT. If AUTOCOMMIT is set to 1 (the default), then each SQL statement (within a
transaction or not) is considered a complete transaction and committed by default when it finishes. When
AUTOCOMMIT is set to 0, by issuing the SET AUTOCOMMIT=0 command, the subsequent series of
statements acts like a transaction and no activities are committed until an explicit COMMIT statement is
issued.
Reference Books:
1.Silberschatz A., Korth H., Sudarshan S., "Database System Concepts", McGraw Hill Publishers, ISBN 0-07-
120413-X, 6th edition

Program:

/*
Assignment No. A1
Roll No.:
Full Name:
Title: Study of Open Source Relational Databases: MySQL
*/
<Your program here>
/* Output:
(As displayed after execution of above program.)
*/

Conclusion: In this way we study the MySQL database, datatypes in MySQL and simple
commands in MySQL.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
14

Assignment No. A2
Title: Design and Develop SQL DDL statements which demonstrate the use of SQL Objects
such as Table, View, Index, Sequence, Synonym.
Problem Statement / Aim: Upon Completion of this assignment students should able to learn

1. Creating Tables using MySQL database

2. Creating View using MySQL database

3. Creating Index and Sequence on tables

3. Creating Synonym

Theory:
Data Definition Languages (DDL)

Data definition language contains the commands which are used to create and destroy the databases and
their objects (like table, view, index etc)

Following are commands under DDL

1. To create the database instance- CREATE


2. To alter the structure of database- ALTER
3. To rename database instances- RENAME
4. To drop the instances- DROP

A) DDL Commands on database object: Table

The table creation command requires the following details −

 Name of the table


 Name of the fields
 Definitions for each field
Syntax
Here is a generic SQL syntax to create a MySQL table –

CREATE TABLE table_name (column_name column_type);


Now, we will create the following table in the data1 database.

root@host# mysql -u root -p


Enter password:*******
mysql> use data1;
Database changed
mysql>create table Employee(

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
15

employee_no INT NOT NULL AUTO_INCREMENT,


employee_name varchar(10) NOT NULL,
joining_date DATE,
salary INT,
PRIMARY KEY(employee_no)
);
Query OK, 0 rows affected (0.16 sec)
mysql>

Here, a few items need explanation −

 Field Attribute NOT NULL is being used because we do not want this field to be NULL. So, if a
user will try to create a record with a NULL value, then MySQL will raise an error.

 Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available
number to the id field.

 Keyword PRIMARY KEY is used to define a column as a primary key. You can use multiple
columns separated by a comma to define a primary key.

1) Creating Table from Existing Table

Consider the existing table Employee

Create table table_name as select * from existing_table_name;

For Example

Create table newEmployee1 as select * from Employee;

// The newly created table newEmployee1 will include all the field and records as in Employee table

2) Creating Table having specific field but all the records from existing table

Syntax:

Create table table_name as select filed1,field2… from existing_table Name;

For example:

Create table newEmployee2 as select Employee_no,Employee_name from Employee;

B) Modifying Table

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
16

ALTER TABLE query is used to modify structure of a table which is already exists in the
database. We can add, delete, or modify column
1) Adding new column in a table

Syntax:

ALTER TABLE table_name ADD Columan-name datatype;

For example

Create table Employee1(Employee_no integer(3),


Employee_name varchar(20),
joining_date date,
Salary integer(6));

ALTER TABLE Employee1 ADD Department varchar(15);

2) Dropping column from table


Syntax: ALTER TABLE table_name DROP COLUMN Column_name;

ALTER TABLE Employee1 DROP column Department;

3) Modifying Column of a table

Syntax: ALTER TABLE table_name MODIFY COLUMN column_name data_type

ALTER TABLE Employee1 MODIFY COLUMN Employee_no varchar(4);

4) Renaming Table

Syntax: rename table current_table to new_table_name;

Rename table Employee1 to Emptable;

5) Drop Table (User to delete the table)


Syntax: drop table table_name;

drop table Emptable;

DDL Commands on Views

In SQL a view is virtual table containing the records of one or more tables based on SQL statement
executed. Just like a real table, view contains rows and columns. You can add SQL functions, WHERE
and JOIN statement to a view and presents the data as if the data were coming from one single table.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
17

The changes made in a table get automatically reflected in original table and vice versa.

A) Creating View

Consider we have existing table as Employee (Employee_no, Employee_name, joining_date,salary)

1) Creating view having all records and fields from existing table
Syntax:
CREATE or replace VIEW view_name as
SELECT Column1,Column2,… FROM table_name Where Condition;

create table Employee2(Employee_no int,Employee_name varchar(10),joining_


date date,salary int);

Create or replace view Emp_view1 as select * from Employee2;

2) Creating view having specific fields but all the records from existing table
Syntax:
Create or replace view view_name as
Select field1,field2… from existing_table_name;

Create or replace view Emp_view2 as select Employee_no,Employee_name from Employee;

B) Updating View

Updating query is used to update the records of view. Updation in view reflects the original table also.

Syntax:

UPDATE view_name

Set field_name=new_Value where condition;

UPDATE Emp_view1 set Salary=73000 where Employee_no=101;

C)Dropping View

Syntax: DROP view view_name

DROP view Emp_view2;

DDL Commands on Index

An Index is a pointer to data in a table. An index in a database is similar to the alphabetical index of a
book presents at the end of book.

Indexes can be created or dropped with no effect on data.

A) Creating Index

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
18

CREATE INDEX statement is used to create an INDEX. In this statement we have to mention name
of the index, the table and column and whether the index is in ascending or descending order.

Syntax:

CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column1, column2, ...);

CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

ASC or DESC is placed at end of column for ascending or descending order.

CREATE INDEX emp_ind1 on Emp(Emo_no ASC);

B) Displaying Index

To display index information regarding table following query is used

Syntax: show index from table_name;

Show index from Emp;

C) Dropping Index

To drop index of a table following query is used

Syntax: Drop index index_name on table_name;

Drop index emp1_ind1 on emp;

DDL Commands of Sequence:

A Sequence is a set of integers. Sequences are generated in order as per requirements.Sequences are used
to create unique values for the rows.

Create table emp2(empno int auto_increment,ename varchar(10),sal int, primary key(empno));

DDL Commands on Synonym

A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and
other database objects. You generally use synonyms when you are granting access to an object from
another schema and you don't want the users to have to worry about knowing which schema owns the
object.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
19

Syntax: In Oracle the commands is as follows

create synonym Cutomers for LongTablePrefix_Customers;

Program:
//Create Table
mysql> use dbms;
Database changed
mysql> create table Employee(
-> employee_no INT NOT NULL AUTO_INCREMENT,
-> employee_name varchar(10) NOT NULL,
-> joining_date DATE,
-> salary INT,
-> PRIMARY KEY(employee_no)
-> );
Query OK, 0 rows affected (0.34 sec)

1)Creating Table from Existing Table

mysql> Create table newEmployee1 as select * from Employee;


Query OK, 0 rows affected (0.37 sec)
Records: 0 Duplicates: 0 Warnings: 0

2)Creating Table having specific field but all the records from existing table

mysql> Create table newEmployee2 as select Employee_no,Employee_name from Employee;


Query OK, 0 rows affected (0.30 sec)
Records: 0 Duplicates: 0 Warnings: 0

B)Modifying Table

1)Adding new column in a table

mysql> Create table Employee1(Employee_no integer(3),


-> Employee_name varchar(20),
-> joining_date date,
-> Salary integer(6));
Query OK, 0 rows affected (0.35 sec)
mysql> ALTER TABLE Employee1 ADD Department varchar(15);
Query OK, 0 rows affected (0.41 sec)
Records: 0 Duplicates: 0 Warnings: 0

2)Dropping column from table

ALTER TABLE Employee1 DROP column Department;


Query OK, 0 rows affected (0.50 sec)
Records: 0 Duplicates: 0 Warnings: 0

3)Modifying Column of a table

mysql> ALTER TABLE Employee1 MODIFY COLUMN Employee_no varchar(4);

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
20

Query OK, 0 rows affected (0.89 sec)


Records: 0 Duplicates: 0 Warnings: 0

4)Renaming Table
mysql> Rename table Employee1 to Emptable;
Query OK, 0 rows affected (0.38 sec)

5)Drop Table (User to delete the table)

mysql> drop table Emptable;


Query OK, 0 rows affected (0.20 sec)
Creating view
mysql> create table Employee2(Employee_no int,Employee_name varchar(10),joining_
date date,salary int);
Query OK, 0 rows affected (0.31 sec)
mysql> Create or replace view Emp_view1 as select * from Employee2;
Query OK, 0 rows affected (0.06 sec)
Updating View
mysql> insert into Emp_view1 values(101,'gajanan','2017-01-06',45000);
Query OK, 1 row affected (0.14 sec)
mysql> select * from Emp_view1;
+-------------+---------------+--------------+--------+
| Employee_no | Employee_name | joining_date | salary |
+-------------+---------------+--------------+--------+
| 101 | gajanan | 2017-01-06 | 45000 |
+-------------+---------------+--------------+--------+
1 row in set (0.00 sec)

mysql> UPDATE Emp_view1 set Salary=73000 where Employee_no=101;


Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from Emp_view1;


+-------------+---------------+--------------+--------+
| Employee_no | Employee_name | joining_date | salary |
+-------------+---------------+--------------+--------+
| 101 | gajanan | 2017-01-06 | 73000 |
+-------------+---------------+--------------+--------+
1 row in set (0.00 sec)

Creating Index
mysql> create table emp(empno int,name varchar(7),salary int);
Query OK, 0 rows affected (0.32 sec)

mysql> insert into emp values(101,'gajanan',45000);


Query OK, 1 row affected (0.09 sec)

mysql> insert into emp values(1,'gajanan1',65000);


ERROR 1406 (22001): Data too long for column 'name' at row 1
mysql> insert into emp values(1,'gaju1',65000);
Query OK, 1 row affected (0.08 sec)

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
21

mysql> insert into emp values(1011,'gaju2',3300);


Query OK, 1 row affected (0.03 sec)

mysql> CREATE INDEX emp1_ind1 on emp(empno);


Query OK, 0 rows affected (0.38 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> show index from emp;


+-------+------------+-----------+--------------+-------------+-----------+-----
--------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Card
inality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-----------+--------------+-------------+-----------+-----
--------+----------+--------+------+------------+---------+---------------+
| emp | 1 | emp1_ind1 | 1 | empno |A |
3 | NULL | NULL | YES | BTREE | | |
+-------+------------+-----------+--------------+-------------+-----------+-----
--------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec)

mysql>

Creating Sequence

mysql> Create table emp2(empno int auto_increment,ename varchar(10),sal int, primary key(empno));
Query OK, 0 rows affected (0.27 sec)
mysql> insert into emp2 values(1,'gajanan',20000);
Query OK, 1 row affected (0.10 sec)

mysql> insert into emp2 values(default,'gajanan',20000);


Query OK, 1 row affected (0.07 sec)

mysql> insert into emp2 values(default,'gajanan',20000);


Query OK, 1 row affected (0.05 sec)

mysql> select * from emp2;


+-------+---------+-------+
| empno | ename | sal |
+-------+---------+-------+
| 1 | gajanan | 20000 |
| 2 | gajanan | 20000 |
| 3 | gajanan | 20000 |
+-------+---------+-------+
3 rows in set (0.00 sec)

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
22

/*
Assignment No. A2
Roll No.:
Full Name:
Title: Design and Develop SQL DDL statements which demonstrate the use of SQL Objects such as
Table, View, Index, Sequence, Synonym.
*/

<Your program here>

/* Output:
(As displayed after execution of above program.)
*/

Conclusion: In this way, we developed SQL DDL statements which demonstrate the use of SQL
objects such as Table, view, Index, Sequence, Synonym.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
23

Assignment No. A3
Title: Design at Least 10 SQL queries for suitable database applications using SQL DML
statement: Insert, Select, Update, Delete with operators, functions, and set operators.

Problem Statement / Aim: Upon Completion of this assignment students should able to learn

1. Insert data into database tables

2. Updating data into tables

3. Deleting data from tables

3. Use of aggregate functions in SQL

4. Use of operators in SQL

Theory:

Data Manipulation Language (DML)

The data manipulation language (DML) is used for accessing and manipulating data in a database. It
allows users to access, insert, update and delete data from the database.

To insert record into the table-INSERT

To access or read records from table –SELECT

Update the record in table- UPDATE

Delete the records from the table- DELETE

Problem Statement:

Create a table Employee( emp_no, emp_name,joining_date, salary)

product_details(product_id,product_name,quantity,prices)

sales_details(sale_no,product_id,quantity,price,customer_name)

and execute the following queries on Employee Table:

1) Insert 5 record into Employee Table


2) Retrieve all the record from Table Employee
3) Retrieve all records from column emp_no and emp_name only
4) Retrieve the salary from Employee where salary >8000;
5) Retrieve the salary using distinct clause from Employee
6) Update the Salary to 50000 of Employee whose emp_no =101

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
24

7) Delete the Employee record from table whose emp_no =106


8) Retrieve the records of Employee whose salary is in between 8000 to 30000
9) Retrieve the records of Employee whose salary is 8000 and 30000
10) Display the records of Employee who join in 2015
11) Retrieve the minimum salary of Employee
12) Retrieve the highest salary of the Employee
13) Retrieve the count of Employee who join in 1999
14) Find the total salary amount paid to the employee
15) Display only joining year of the employee
16) Retrieve the ids of all product even if they were sold or present in the storage room(use union
Operator)
17) Retrieve the ids of all the sold product even if they were sold or present in the storage room(use
union all operator)
18) Retrieve all the ids of all the sold products(use interest operator)
19) Retrieve all the ids of all the sold products(use minus operator)

Theory:-

1. Inserting a Single row of data into a table

Syntax:

Insert into table_name values(value1,valu2……);

2. Inserting data into a table from another table

Syntax:

Insert into table_name select Column1,Column2 from table_name;

3. Retrieve data from tables

SELECT Query

SELECT query is used to retrieve the data from database.SELECT query never make any change
in database.

Syntax:

SELECT Column_name1,column_name2…..from table_name;

If we want to retrieve data from all the column of a table then instead of writing all the column
name use

‘*’ . The ‘*’ symbol represent all the column.

SELECT * from table_name;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
25

With SELECT statement different clauses can be used to display the data as per our requirement.

A) WHERE Clause

WHERE clause is used to specify condition in SELECT statement while fetching records from the
database. The records satisfying the condition given by where clause are retrieved.

SELECT Column_name1,column_name2…..from table_name WHERE condition;

B) DISTINCT Clause

This clause is used to avoid selection of duplicate rows.

SELECT distinct (Column_name) from Employee;

C) ORDERBY Clause

To arrange the displayed rows in ascending or descending order of a given column, ORDERBY Clause is
used.

SELECT * from table_name orderby Column_name desc/asc;

ASC or DESC words are used to maintaining ascending or descending order.

4. Modifying Data in Tables

To make changes in the database update command is used.The update command consists of ‘set’ Clause
and optional ‘where’ clause. ‘WHERE’ clause is used to make changes in specific records.

Syntax:

Update table_name set Column_name=new_value[where condition];

5. Remove records from table

Delete

As per requirement , the records from existing table can be removed using delete command.Delete
command can have ‘Where clause optionally.

Syntax:

SELECT Column_name1,column_name2…..from table_name [WHERE condition];

BETWEEN ,IN, LIKE Predicate

a) BETWEEN predicate

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
26

Between predicate is used to specify certain range of values. The AND keyword is used in this predicate.

Syntax:

Test_expression [NOT] Between begin_expression AND end_expression


For example:
Select * from Employee where salary between 10000 and 20000;

b) IN predicate

IN Predicate particularly determines where the value of expression to test matches any value in
specified the list.

For example

Manager wants to view records of employees whose salary is 8000 and 30000

The query will be

Select * from Employee where salary in(8000,30000);

Manager wants to view records of employee whose salary is not 8000 and 30000

Select * from Employee where salary NOT IN(8000,30000);

c) LIKE Predicate

LIKE operator determines whether a specific character string matches the given pattern or not.

For Example

Display the records of employee who join in 2015

Select * from Employee where joining_date LIKE ‘2015%’;

Disply records of Employee who didn’t join in 2015

Select * from Employee where joining_date not like ‘2015%’;

Aggregate Functions:

1)Min( ) –This function returns smallest value from specified column of the table

For example

Query to retrieve record of employee who gets least salary as compare to other employee

Select * from Employee where Salary=(select min(salary) from Employee;

2)Max( )- This function return greatest value from specified column of the table.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
27

Query to retrieve record of employee who gets maximum salary as compare to other employee

Select * from Employee where Salary=(select max(salary) from Employee;

3)Count( )- This function return total number of values of specified column of the table

For example

Query to retrieve count of employee who join in 2015 year

Select count(Employee_no) from Employee where joining_date like’2015%’;

4)Sum( )- This function returns the sum of all the values of specified column of the table.

For example

Query to find total salary amount paid to all the employee

Select Sum(Salary) from Employee;

Scalar Functions in SQL to Perform DML operations on table Data.

1)MID( )- This functions is used to extract substrings from column values of string type in a table

Syntax:

Select MID(Column_name,start,length) from table_name;

For example

Select MID(joining_date,1,4)from Employee;

2)LCASE( )- This functions is used to convert value of string column in Lowercase characters.

Select LCASE(Column_name) from table_name;

3)UCASE( )- This functions is used to convert value of string column in Uppercase characters.

Select UCASE(Column_name) from table_name;

4)ROUND( ) – This function is used to round a numeric field to number of nearest integer. It is used on
Decimal point values.

Select round(Column_name) from table_name;

SET operations in SQL queries to perform DML operations on table data.

The Different set operations are as follows.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
28

1)UNION- The union operator returns all distinct rows selected by either query;

Syntax:

Select column_name from table1


Union
Select Column_name from table2;

2)UNION ALL- This returns all rows selected by either query including duplicates.

Syntax:

Select column_name from table1


Union all
Select Column_name from table2;

3)INTERSECT- This operator returns only those rows which are common to both the queries.

Select column_name from table1


intersect
Select Column_name from table2;

4)MINUS- Minus operator displays the rows which are present in the first query but absent in the second
query with no duplicates and data is arranged in ascending order by default.

Select column_name from table1


minus
Select Column_name from table2;

Program:
mysql> create table Employee(emp_no int,emp_name varchar(10),joining_date date,salray int);
Query OK, 0 rows affected (0.48 sec)

1) Insert 5 record into Employee Table

mysql> insert into Employee values(101,'Rajesh','1995-11-02',12000);


Query OK, 1 row affected (0.12 sec)

mysql> insert into Employee values(102,'Swati','2015-01-07',20000);


Query OK, 1 row affected (0.06 sec)

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
29

mysql> insert into Employee values(103,'Vedant','1999-05-03',30000);


Query OK, 1 row affected (0.07 sec)

mysql> insert into Employee values(104,'Vedika','2005-02-10',52000);


Query OK, 1 row affected (0.06 sec)

mysql> insert into Employee values(105,'Ankita','2006-02-11',8000);


Query OK, 1 row affected (0.04 sec)

mysql> insert into Employee values(106,'Ankur','2017-03-15',6000);


Query OK, 1 row affected (0.05 sec)

mysql>

2) Retrieve all the record from Table Employee

mysql> select * from Employee;


+--------+----------+--------------+-------+
| emp_no | emp_name | joining_date | salary |
+--------+----------+--------------+-------+
| 101 | Rajesh | 1995-11-02 | 12000 |
| 102 | Swati | 2015-01-07 | 20000 |
| 103 | Vedant | 1999-05-03 | 30000 |
| 104 | Vedika | 2005-02-10 | 52000 |
| 105 | Ankita | 2006-02-11 | 8000 |
| 106 | Ankur | 2017-03-15 | 6000 |
+--------+----------+--------------+-------+
6 rows in set (0.06 sec)

3) Retrieve all records from column emp_no and emp_name only


mysql> select emp_no ,emp_name from Employee;
+--------+----------+
| emp_no | emp_name |
+--------+----------+
| 101 | Rajesh |
| 102 | Swati |
| 103 | Vedant |
| 104 | Vedika |
| 105 | Ankita |
| 106 | Ankur |
+--------+----------+
6 rows in set (0.00 sec)

4) Retrieve the salary from Employee where salary >8000;

mysql> select * from Employee where salary>8000;


+--------+----------+--------------+--------+
| emp_no | emp_name | joining_date | salary |
+--------+----------+--------------+--------+

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
30

| 101 | Rajesh | 1995-11-02 | 12000 |


| 102 | Swati | 2015-01-07 | 20000 |
| 103 | Vedant | 1999-05-03 | 30000 |
| 104 | Vedika | 2005-02-10 | 52000 |
+--------+----------+--------------+--------+
4 rows in set (0.02 sec)

5) Retrieve the salary using distinct clause from Employee

mysql> select distinct(salary) from Employee;


+--------+
| salary |
+--------+
| 12000 |
| 20000 |
| 30000 |
| 52000 |
| 8000 |
| 6000 |
+--------+
6 rows in set (0.06 sec)

6)Update the Salary to 50000 of Employee whose emp_no =101


mysql> update Employee set salary=50000 where emp_no=101;
Query OK, 1 row affected (0.09 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from Employee;


+--------+----------+--------------+--------+
| emp_no | emp_name | joining_date | salary |
+--------+----------+--------------+--------+
| 101 | Rajesh | 1995-11-02 | 50000 |
| 102 | Swati | 2015-01-07 | 20000 |
| 103 | Vedant | 1999-05-03 | 30000 |
| 104 | Vedika | 2005-02-10 | 52000 |
| 105 | Ankita | 2006-02-11 | 8000 |
| 106 | Ankur | 2017-03-15 | 6000 |
+--------+----------+--------------+--------+
6 rows in set (0.00 sec)

7)Delete the Employee record from table whose emp_no =106

mysql> delete from Employee where emp_no =106;


Query OK, 1 row affected (0.06 sec)

mysql> select * from Employee;


+--------+----------+--------------+--------+
| emp_no | emp_name | joining_date | salary |
+--------+----------+--------------+--------+
| 101 | Rajesh | 1995-11-02 | 50000 |
| 102 | Swati | 2015-01-07 | 20000 |

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
31

| 103 | Vedant | 1999-05-03 | 30000 |


| 104 | Vedika | 2005-02-10 | 52000 |
| 105 | Ankita | 2006-02-11 | 8000 |
+--------+----------+--------------+--------+
5 rows in set (0.00 sec)

8) Retrieve the records of Employee whose salary is in between 8000 to 30000

mysql> select * from Employee where salary between 8000 and 30000;
+--------+----------+--------------+--------+
| emp_no | emp_name | joining_date | salary |
+--------+----------+--------------+--------+
| 102 | Swati | 2015-01-07 | 20000 |
| 103 | Vedant | 1999-05-03 | 30000 |
| 105 | Ankita | 2006-02-11 | 8000 |
+--------+----------+--------------+--------+
3 rows in set (0.00 sec)

9)Retrieve the records of Employee whose salary is 8000 and 30000


mysql> select * from Employee where salary in(8000,30000);
+--------+----------+--------------+--------+
| emp_no | emp_name | joining_date | salary |
+--------+----------+--------------+--------+
| 103 | Vedant | 1999-05-03 | 30000 |
| 105 | Ankita | 2006-02-11 | 8000 |
+--------+----------+--------------+--------+
2 rows in set (0.01 sec)
10)Display the records of Employee who join in 2015

mysql> select * from Employee where joining_date Like '2015%';


+--------+----------+--------------+--------+
| emp_no | emp_name | joining_date | salary |
+--------+----------+--------------+--------+
| 102 | Swati | 2015-01-07 | 20000 |
+--------+----------+--------------+--------+
1 row in set, 1 warning (0.10 sec)

11)Retrieve the minium salary of Employee


mysql> select MIN(salary) from Employee;
+-------------+
| MIN(salary) |
+-------------+
| 8000 |
+-------------+
1 row in set (0.10 sec)

12)Retrieve the highest salary of the Employee

mysql> select MAX(salary) from Employee;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
32

+-------------+
| MAX(salary) |
+-------------+
| 52000 |
+-------------+
1 row in set (0.00 sec)

13)Retrieve the count of Employee who join in 2015


mysql> select count(Emp_no) from Employee where joining_date like '1999%';
+---------------+
| count(Emp_no) |
+---------------+
| 1|
+---------------+
1 row in set, 1 warning (0.02 sec)

14)Find the total salary amount paid to the employee

mysql> select sum(salary) from Employee;


+-------------+
| sum(salary) |
+-------------+
| 160000 |
+-------------+
1 row in set (0.07 sec)

15)Display only joining year of the employee

mysql> select MID(joining_date,1,4) from Employee;


+-----------------------+
| MID(joining_date,1,4) |
+-----------------------+
| 1995 |
| 2015 |
| 1999 |
| 2005 |
| 2006 |
+-----------------------+
5 rows in set (0.02 sec)

mysql> create table product_details(product_id int,product_name varchar(10),quantity int,price int);


Query OK, 0 rows affected (0.39 sec)

mysql> insert into product_details values(5001,'pendrive',100,900);


Query OK, 1 row affected (0.09 sec)

mysql> insert into product_details values(5002,'Harddisk',200,3500);


Query OK, 1 row affected (0.05 sec)

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
33

mysql> insert into product_details values(5003,'Headphone',1000,600);


Query OK, 1 row affected (0.14 sec)

mysql> insert into product_details values(5004,'DVD',20,1500);


Query OK, 1 row affected (0.03 sec)

mysql> insert into product_details values(5005,'Speaker',600,1200);


Query OK, 1 row affected (0.09 sec)

mysql> insert into product_details values(5006,'headphone',1000,400);


Query OK, 1 row affected (0.10 sec)
mysql> select * from product_details;
+------------+--------------+----------+-------+
| product_id | product_name | quantity | price |
+------------+--------------+----------+-------+
| 5001 | pendrive | 100 | 900 |
| 5002 | Harddisk | 200 | 3500 |
| 5003 | Headphone | 1000 | 600 |
| 5004 | DVD | 20 | 1500 |
| 5005 | Speaker | 600 | 1200 |
| 5006 | headphone | 1000 | 400 |
+------------+--------------+----------+-------+
6 rows in set (0.01 sec)

mysql> create table sales_details(sale_no int,product_id int,quantity int,price int,customer_name


varchar(10));
Query OK, 0 rows affected (0.27 sec)

mysql> insert into sales_details values(2001,5001,50,900,'Savani');


Query OK, 1 row affected (0.11 sec)

mysql> insert into sales_details values(2002,5004,10,1500,'Savani');


Query OK, 1 row affected (0.06 sec)

mysql> insert into sales_details values(2003,5003,120,600,'Deepak');


Query OK, 1 row affected (0.06 sec)

mysql> insert into sales_details values(2004,5005,420,1200,'Harsh');


Query OK, 1 row affected (0.13 sec)

mysql> insert into sales_details values(2005,5002,40,3500,'Akash');


Query OK, 1 row affected (0.12 sec)

mysql> select * from sales_details;


+---------+------------+----------+-------+---------------+
| sale_no | product_id | quantity | price | customer_name |
+---------+------------+----------+-------+---------------+
| 2001 | 5001 | 50 | 900 | Savani |
| 2002 | 5004 | 10 | 1500 | Savani |

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
34

| 2003 | 5003 | 120 | 600 | Deepak |


| 2004 | 5005 | 420 | 1200 | Harsh |
| 2005 | 5002 | 40 | 3500 | Akash |
+---------+------------+----------+-------+---------------+
5 rows in set (0.00 sec)

16)Retrieve the ids of all product even if they were sold or present in the storage room(use union
Operator)
mysql> select product_id from product_details union select product_id from sales
_details;
+------------+
| product_id |
+------------+
| 5001 |
| 5002 |
| 5003 |
| 5004 |
| 5005 |
| 5006 |
+------------+
6 rows in set (0.00 sec)

17)Retrieve the ids of all the sold product even if they were sold or present in the storage room(use union
all operator)

mysql> select product_id from product_details union all select product_id from sales_details;
+------------+
| product_id |
+------------+
| 5001 |
| 5002 |
| 5003 |
| 5004 |
| 5005 |
| 5006 |
| 5001 |
| 5004 |
| 5003 |
| 5005 |
| 5002 |
+------------+
11 rows in set (0.00 sec)

18)Retrieve all the ids of all the sold products(use interest operator)

SQL> create table sales_details(sale_no int,product_id int,quantity int,price


t,customer_name varchar(10));

Table created.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
35

SQL> insert into sales_details values(2001,5001,50,900,'Savani');

1 row created.

SQL> insert into sales_details values(2002,5004,10,1500,'Savani');

1 row created.

SQL> insert into sales_details values(2003,5003,120,600,'Deepak');

1 row created.

SQL> insert into sales_details values(2004,5005,420,1200,'Harsh');

1 row created.

SQL> insert into sales_details values(2005,5002,40,3500,'Akash');

1 row created.

SQL> select * from sales_details;

SALE_NO PRODUCT_ID QUANTITY PRICE CUSTOMER_N


---------- ---------- ---------- ---------- ----------
2001 5001 50 900 Savani
2002 5004 10 1500 Savani
2003 5003 120 600 Deepak
2004 5005 420 1200 Harsh
2005 5002 40 3500 Akash

SQL> create table product_details(product_id int,product_name varchar(10),quan


ty int,price int);

Table created.

SQL> insert into product_details values(5001,'pendrive',100,900);

1 row created.

SQL> insert into product_details values(5002,'Harddisk',200,3500);

1 row created.

SQL> insert into product_details values(5003,'Headphone',1000,600);

1 row created.

SQL> insert into product_details values(5004,'DVD',20,1500);

1 row created.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
36

SQL> insert into product_details values(5005,'Speaker',600,1200);

1 row created.

SQL> select * from product_details;

PRODUCT_ID PRODUCT_NA QUANTITY PRICE


---------- ---------- ---------- ----------
5001 pendrive 100 900
5002 Harddisk 200 3500
5003 Headphone 1000 600
5004 DVD 20 1500
5005 Speaker 600 1200

SQL> select product_id from product_details intersect select product_id from saes_details;

PRODUCT_ID
----------
5001
5002
5003
5004
5005

SQL> select *from product_details;

PRODUCT_ID PRODUCT_NA QUANTITY PRICE


---------- ---------- ---------- ----------
5001 pendrive 100 900
5002 Harddisk 200 3500
5003 Headphone 1000 600
5004 DVD 20 1500
5005 Speaker 600 1200

SQL> select *from sales_details;

SALE_NO PRODUCT_ID QUANTITY PRICE CUSTOMER_N


---------- ---------- ---------- ---------- ----------
2001 5001 50 900 Savani
2002 5004 10 1500 Savani
2003 5003 120 600 Deepak
2004 5005 420 1200 Harsh

SQL> delete from sales_details where sale_no=2005;

1 row deleted.
SQL> select *from product_details;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
37

PRODUCT_ID PRODUCT_NA QUANTITY PRICE


---------- ---------- ---------- ----------
5001 pendrive 100 900
5002 Harddisk 200 3500
5003 Headphone 1000 600
5004 DVD 20 1500
5005 Speaker 600 1200

SQL> select *from sales_details;

SALE_NO PRODUCT_ID QUANTITY PRICE CUSTOMER_N


---------- ---------- ---------- ---------- ----------
2001 5001 50 900 Savani
2002 5004 10 1500 Savani
2003 5003 120 600 Deepak
2004 5005 420 1200 Harsh

SQL> select product_id from product_details minus select product_id from sales_d
etails;

PRODUCT_ID
----------
5002

/*
Assignment No. A3
Roll No.:
Full Name:
Title: Design at Least 10 SQL queries for suitable database applications using SQL DML
statement: Insert, Select, Update, Delete with operators, functions, and set operators.
*/
<Your program here>
/* Output:
(As displayed after execution of above program.)
*/

Conclusion: Thus we have designed and developed SQL queries which demonstrate the use
SQL queries such as insert, delete, update and use of operator, functions and set operators.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
38

Assignment No. A4
Title: Design at Least 10 SQL queries for suitable database applications using SQL DML
statement: All types of joins and sub-queries.

Problem Statement / Aim: Upon Completion of this assignment students should able to learn

1. Concept of joins in SQL

2. Working of Inner join

3. Operations of Outer join

3. Operation of Left Outer Join

4. Operation of Right Outer Join

5. Sub queries in SQL

Theory:

SQL Join

A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
39

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico

3 Antonio Moreno Taquería Antonio Moreno Mexico

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers"
table. The relationship between the two tables above is the "CustomerID" column.

Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records
that have matching values in both tables:

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
and it will produce something like this:

OrderID CustomerName OrderDate

10308 Ana Trujillo Emparedados y helados 9/18/1996

10365 Antonio Moreno Taquería 11/27/1996

10383 Around the Horn 12/16/1996

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
40

10355 Around the Horn 11/15/1996

10278 Berglunds snabbköp 8/12/1996

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the
right table
 RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from
the left table
 FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

SQL INNER JOIN Keyword

The INNER JOIN keyword selects records that have matching values in both tables.

INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
41

SQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the
right table (table2). The result is NULL from the right side, if there is no match.

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;

SQL RIGHT JOIN Keyword

The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from
the left table (table1). The result is NULL from the left side, when there is no match.

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

SQL FULL OUTER JOIN Keyword

The FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or right
(table2) table records.

Note: FULL OUTER JOIN can potentially return very large result-sets.

FULL OUTER JOIN Syntax


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

Program:
mysql> select * from product_details;
+------------+--------------+----------+-------+
| product_id | product_name | quantity | price |
+------------+--------------+----------+-------+
| 5001 | pendrive | 100 | 900 |
| 5002 | Harddisk | 200 | 3500 |
| 5003 | Headphone | 1000 | 600 |
| 5004 | DVD | 20 | 1500 |
| 5005 | Speaker | 600 | 1200 |
| 5006 | headphone | 1000 | 400 |
+------------+--------------+----------+-------+
6 rows in set (0.04 sec)

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
42

mysql> select * from sales_details;


+---------+------------+----------+-------+---------------+
| sale_no | product_id | quantity | price | customer_name |
+---------+------------+----------+-------+---------------+
| 2001 | 5001 | 50 | 900 | Savani |
| 2002 | 5004 | 10 | 1500 | Savani |
| 2003 | 5003 | 120 | 600 | Deepak |
| 2004 | 5005 | 420 | 1200 | Harsh |
| 2005 | 5002 | 40 | 3500 | Akash |
+---------+------------+----------+-------+---------------+
5 rows in set (0.00 sec)

mysql>

INNER JOIN

mysql> select product_details.product_id,product_name ,sales_details.customer_na


me ,product_details.quantity,product_details.price from product_details INNER JO
IN sales_details on product_details.product_id=sales_details.product_id;
+------------+--------------+---------------+----------+-------+
| product_id | product_name | customer_name | quantity | price |
+------------+--------------+---------------+----------+-------+
| 5001 | pendrive | Savani | 100 | 900 |
| 5002 | Harddisk | Akash | 200 | 3500 |
| 5003 | Headphone | Deepak | 1000 | 600 |
| 5004 | DVD | Savani | 20 | 1500 |
| 5005 | Speaker | Harsh | 600 | 1200 |
+------------+--------------+---------------+----------+-------+
5 rows in set (0.00 sec)

LEFT OUTER JOIN

mysql> select product_details.product_id,product_name ,sales_details.customer_na


me ,product_details.quantity,product_details.price from product_details LEFT OUT
ER JOIN sales_details on product_details.product_id=sales_details.product_id;
+------------+--------------+---------------+----------+-------+
| product_id | product_name | customer_name | quantity | price |
+------------+--------------+---------------+----------+-------+
| 5001 | pendrive | Savani | 100 | 900 |
| 5004 | DVD | Savani | 20 | 1500 |
| 5003 | Headphone | Deepak | 1000 | 600 |
| 5005 | Speaker | Harsh | 600 | 1200 |
| 5002 | Harddisk | Akash | 200 | 3500 |
| 5006 | headphone | NULL | 1000 | 400 |

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
43

+------------+--------------+---------------+----------+-------+
6 rows in set (0.00 sec)

mysql>

RIGHT OUTER JOIN


mysql> select product_details.product_id,product_name ,sales_details.customer_na
me ,product_details.quantity,product_details.price from product_details RIGHT OU
TER JOIN sales_details on product_details.product_id=sales_details.product_id;
+------------+--------------+---------------+----------+-------+
| product_id | product_name | customer_name | quantity | price |
+------------+--------------+---------------+----------+-------+
| 5001 | pendrive | Savani | 100 | 900 |
| 5002 | Harddisk | Akash | 200 | 3500 |
| 5003 | Headphone | Deepak | 1000 | 600 |
| 5004 | DVD | Savani | 20 | 1500 |
| 5005 | Speaker | Harsh | 600 | 1200 |
+------------+--------------+---------------+----------+-------+
5 rows in set (0.00 sec)

mysql>

/*
Assignment No. A4
Roll No.:
Full Name:
Title: Design at Least 10 SQL queries for suitable database applications using SQL DML
statement: All types of joins and sub-queries.
*/

<Your program here>

/* Output:
(As displayed after execution of above program.)
*/

Conclusion: Thus we have design queries using inner, outer and full join and also design queries
that have sub queries.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
44

Assignment No. A5
Title: Unnamed PL/SQL code block: Use of Control structure and Exception handling is
mandatory. Write a PL/SQL block of code for the following requirements:-
Schema:
 Borrower(Rollin, Name, DateofIssue, NameofBook, Status)
 Fine(Roll_no,Date,Amt)
 Accept roll_no & 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 & 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.

Problem Statement / Aim: Upon Completion of this assignment students should able to learn

1. Concept of PL/SQL block

2. Operation using PL/SQL block like Control structure and Exception Handling.

3. How to Write PL/SQL Block.

4. Understand the difference between PL/SQL and SQL

Theory:

The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database. Following are certain notable
facts about PL/SQL −
 PL/SQL is a completely portable, high-performance transaction-processing language.
 PL/SQL provides a built-in, interpreted and OS independent programming environment.
 PL/SQL can also directly be called from the command-line SQL*Plus interface.
 Direct call can also be made from external programming language calls to database.
 PL/SQL's general syntax is based on that of ADA and Pascal programming language.
 Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.
Features of PL/SQL
PL/SQL has the following features −
 PL/SQL is tightly integrated with SQL.
 It offers extensive error checking.
 It offers numerous data types.
 It offers a variety of programming structures.
 It supports structured programming through functions and procedures.
 It supports object-oriented programming.
 It supports the development of web applications and server pages.
Advantages of PL/SQL
PL/SQL has the following advantages −

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
45

 SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL
supports both static and dynamic SQL. Static SQL supports DML operations and transaction
control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in
PL/SQL blocks.
 PL/SQL allows sending an entire block of statements to the database at one time. This reduces
network traffic and provides high performance for the applications.
 PL/SQL gives high productivity to programmers as it can query, transform, and update data in a
database.
 PL/SQL saves time on design and debugging by strong features, such as exception handling,
encapsulation, data hiding, and object-oriented data types.
 Applications written in PL/SQL are fully portable.
 PL/SQL provides high security level.
 PL/SQL provides access to predefined SQL packages.
 PL/SQL provides support for Object-Oriented Programming.
 PL/SQL provides support for developing Web Applications and Server Pages.
 the PL/SQL programs are divided and written in logical blocks of code. Each block consists of
three sub-parts −
S.No Sections & Description

Declarations
1 This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.

Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory
2 section. It consists of the executable PL/SQL statements of the program. It should have at
least one executable line of code, which may be just a NULL command to indicate that
nothing should be executed.

Exception Handling
3 This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program.
 Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other
PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −
 DECLARE
 <declarations section>
 BEGIN
 <executable command(s)>
 EXCEPTION
 <exception handling>
 END;
 The 'Hello World' Example
 DECLARE
 message varchar2(20):= 'Hello, World!';
 BEGIN
 dbms_output.put_line(message);
 END;
 /

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
46

 The end; line signals the end of the PL/SQL block. To run the code from the SQL command line,
you may need to type / at the beginning of the first blank line after the last line of the code. When
the above code is executed at the SQL prompt, it produces the following result −
 Hello World

 PL/SQL procedure successfully completed.
 The PL/SQL Identifiers
 PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words.
The identifiers consist of a letter optionally followed by more letters, numerals, dollar signs,
underscores, and number signs and should not exceed 30 characters.
 By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent
a numeric value. You cannot use a reserved keyword as an identifier.
 The PL/SQL Delimiters
 A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL −
Delimiter Description

+, -, *, / Addition, subtraction/negation, multiplication, division

% Attribute indicator

' Character string delimiter

. Component selector

(,) Expression or list delimiter

: Host variable indicator

, Item separator

" Quoted identifier delimiter

= Relational operator

@ Remote access indicator

; Statement terminator

:= Assignment operator

=> Association operator

|| Concatenation operator

** Exponentiation operator

<<, >> Label delimiter (begin and end)

/*, */ Multi-line comment delimiter (begin and end)

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
47

-- Single-line comment indicator

.. Range operator

<, >, <=, >= Relational operators

<>, '=, ~=, ^= Different versions of NOT EQUAL


 The PL/SQL Comments
 Program comments are explanatory statements that can be included in the PL/SQL code that you
write and helps anyone reading its source code. All programming languages allow some form of
comments.
 The PL/SQL supports single-line and multi-line comments. All characters available inside any
comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with the
delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */.
 DECLARE
 -- variable declaration
 message varchar2(20):= 'Hello, World!';
 BEGIN
 /*
 * PL/SQL executable statement(s)
 */
 dbms_output.put_line(message);
 END;
 /
 When the above code is executed at the SQL prompt, it produces the following result −
 Hello World

 PL/SQL procedure successfully completed.
The other two data types will be covered in other chapters.
S.No Category & Description

Scalar
1
Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN.

Large Object (LOB)


2 Pointers to large objects that are stored separately from other data items, such as text,
graphic images, video clips, and sound waveforms.

Composite
3 Data items that have internal components that can be accessed individually. For example,
collections and records.

Reference
4
Pointers to other data items.
PL/SQL Scalar Data Types and Subtypes
PL/SQL Scalar Data Types and Subtypes come under the following categories −
S.No Date Type & Description

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
48

Numeric
1
Numeric values on which arithmetic operations are performed.

Character
2
Alphanumeric values that represent single characters or strings of characters.

Boolean
3
Logical values on which logical operations are performed.

Datetime
4
Dates and times.
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype called
INTEGER. You can use the subtypes in your PL/SQL program to make the data types compatible with
data types in other programs while embedding the PL/SQL code in another program, such as a Java
program.
PL/SQL Numeric Data Types and Subtypes
Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −
S.No Data Type & Description

PLS_INTEGER
1
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

BINARY_INTEGER
2
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

BINARY_FLOAT
3
Single-precision IEEE 754-format floating-point number

BINARY_DOUBLE
4
Double-precision IEEE 754-format floating-point number

NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130 to (but not
including) 1.0E126. A NUMBER variable can also represent 0

DEC(prec, scale)
6
ANSI specific fixed-point type with maximum precision of 38 decimal digits

DECIMAL(prec, scale)
7
IBM specific fixed-point type with maximum precision of 38 decimal digits

NUMERIC(pre, secale)
8
Floating type with maximum precision of 38 decimal digits

DOUBLE PRECISION
9 ANSI specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)

10 FLOAT

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
49

ANSI and IBM specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)

INT
11
ANSI specific integer type with maximum precision of 38 decimal digits

INTEGER
12
ANSI and IBM specific integer type with maximum precision of 38 decimal digits

SMALLINT
13
ANSI and IBM specific integer type with maximum precision of 38 decimal digits

REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately 18
decimal digits)
Following is a valid declaration −
DECLARE
num1 INTEGER;
num2 REAL;
num3 DOUBLE PRECISION;
BEGIN
null;
END;
/
When the above code is compiled and executed, it produces the following result −
PL/SQL procedure successfully completed
PL/SQL Character Data Types and Subtypes
Following is the detail of PL/SQL pre-defined character data types and their sub-types −
S.No Data Type & Description

CHAR
1
Fixed-length character string with maximum size of 32,767 bytes

VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes

RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted
by PL/SQL

NCHAR
4
Fixed-length national character string with maximum size of 32,767 bytes

NVARCHAR2
5
Variable-length national character string with maximum size of 32,767 bytes

LONG
6
Variable-length character string with maximum size of 32,760 bytes

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
50

LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted
by PL/SQL

ROWID
8
Physical row identifier, the address of a row in an ordinary table

UROWID
9
Universal row identifier (physical, logical, or foreign row identifier)
PL/SQL Boolean Data Types
The BOOLEAN data type stores logical values that are used in logical operations. The logical values are
the Boolean values TRUE and FALSE and the value NULL.
However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be used in

 SQL statements
 Built-in SQL functions (such as TO_CHAR)
 PL/SQL functions invoked from SQL statements
Variable Declaration in PL/SQL
PL/SQL variables must be declared in the declaration section or in a package as a global variable. When
you declare a variable, PL/SQL allocates memory for the variable's value and the storage location is
identified by the variable name.
The syntax for declaring a variable is −
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL data type or any
user defined data type which we already have discussed in the last chapter. Some valid variable
declarations along with their definition are shown below −
sales number(10, 2);
pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);
When you provide a size, scale or precision limit with the data type, it is called a constrained
declaration. Constrained declarations require less memory than unconstrained declarations. For example

sales number(10, 2);
name varchar2(25);
address varchar2(100);
Initializing Variables in PL/SQL
Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to initialize a
variable with a value other than the NULL value, you can do so during the declaration, using either of
the following −
 The DEFAULT keyword
 The assignment operator
For example −
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';
You can also specify that a variable should not have a NULL value using the NOT NULL constraint. If
you use the NOT NULL constraint, you must explicitly assign an initial value for that variable.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
51

It is a good programming practice to initialize variables properly otherwise, sometimes programs would
produce unexpected results. Try the following example which makes use of various types of variables −
DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
When the above code is executed, it produces the following result −
Value of c: 30
Value of f: 23.333333333333333333

PL/SQL procedure successfully completed.


Variable Scope in PL/SQL
PL/SQL allows the nesting of blocks, i.e., each program block may contain another inner block. If a
variable is declared within an inner block, it is not accessible to the outer block. However, if a variable is
declared and accessible to an outer block, it is also accessible to all nested inner blocks. There are two
types of variable scope −
 Local variables − Variables declared in an inner block and not accessible to outer blocks.
 Global variables − Variables declared in the outermost block or a package.
Following example shows the usage of Local and Global variables in its simple form −
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/
When the above code is executed, it produces the following result −
Outer Variable num1: 95
Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
52

PL/SQL procedure successfully completed.


Assigning SQL Query Results to PL/SQL Variables
You can use the SELECT INTO statement of SQL to assign values to PL/SQL variables. For each item
in the SELECT list, there must be a corresponding, type-compatible variable in the INTO list. The
following example illustrates the concept. Let us create a table named CUSTOMERS −
(For SQL statements, please refer to the SQL tutorial)
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Table Created
Let us now insert some values in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );
The following program assigns values from the above table to PL/SQL variables using the SELECT
INTO clause of SQL −
DECLARE
c_id customers.id%type := 1;
c_name customerS.No.ame%type;
c_addr customers.address%type;
c_sal customers.salary%type;
BEGIN
SELECT name, address, salary INTO c_name, c_addr, c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line
('Customer ' ||c_name || ' from ' || c_addr || ' earns ' || c_sal);
END;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
53

/
When the above code is executed, it produces the following result −
Customer Ramesh from Ahmedabad earns 2000

PL/SQL procedure completed successfully


Basic loop structure encloses sequence of statements in between the LOOP and END
LOOP statements. With each iteration, the sequence of statements is executed and then control resumes
at the top of the loop.
Syntax
The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence of statements;
END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of statements. An EXIT
statement or an EXIT WHEN statement is required to break the loop.
Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.


You can use the EXIT WHEN statement instead of the EXIT statement −
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
exit WHEN x > 50;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
54

END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.


A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement
as long as a given condition is true.
Syntax
WHILE condition LOOP
sequence_of_statements
END LOOP;
Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.


A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value LOOP

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
55

sequence_of_statements;
END LOOP;
Following is the flow of control in a For Loop −
 The initial step is executed first, and only once. This step allows you to declare and initialize any
loop control variables.
 Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the body of the
loop is executed. If it is FALSE, the body of the loop does not execute and the flow of control
jumps to the next statement just after the for loop.
 After the body of the for loop executes, the value of the counter variable is increased or
decreased.
 The condition is now evaluated again. If it is TRUE, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition becomes
FALSE, the FOR-LOOP terminates.
Following are some special characteristics of PL/SQL for loop −
 The initial_value and final_value of the loop variable or counter can be literals, variables, or
expressions but must evaluate to numbers. Otherwise, PL/SQL raises the predefined exception
VALUE_ERROR.
 The initial_value need not be 1; however, the loop counter increment (or decrement) must be
1.
 PL/SQL allows the determination of the loop range dynamically at run time.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

PL/SQL procedure successfully completed.


Reverse FOR LOOP Statement
By default, iteration proceeds from the initial value to the final value, generally upward from the lower
bound to the higher bound. You can reverse this order by using the REVERSE keyword. In such case,
iteration proceeds the other way. After each iteration, the loop counter is decremented.
However, you must write the range bounds in ascending (not descending) order. The following program
illustrates this −

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
56

DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11
value of a: 10

PL/SQL procedure successfully completed.


PL/SQL allows using one loop inside another loop. Following section shows a few examples to illustrate
the concept.
The syntax for a nested basic LOOP statement in PL/SQL is as follows −
LOOP
Sequence of statements1
LOOP
Sequence of statements2
END LOOP;
END LOOP;
The syntax for a nested FOR LOOP statement in PL/SQL is as follows −
FOR counter1 IN initial_value1 .. final_value1 LOOP
sequence_of_statements1
FOR counter2 IN initial_value2 .. final_value2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;
The syntax for a nested WHILE LOOP statement in Pascal is as follows −
WHILE condition1 LOOP
sequence_of_statements1
WHILE condition2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;
Example
The following program uses a nested basic loop to find the prime numbers from 2 to 100 −

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
57

DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

PL/SQL procedure successfully completed.


The Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
PL/SQL supports the following control statements. Labeling loops also help in taking the control outside
a loop. Click the following links to check their details.
S.No Control Statement & Description

EXIT statement
1 The Exit statement completes the loop and control passes to the statement immediately
after the END LOOP.

2 CONTINUE statement

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
58

Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.

GOTO statement
3 Transfers control to the labeled statement. Though it is not advised to use the GOTO
statement in your program.
An exception is an error condition during a program execution. PL/SQL supports programmers to catch
such conditions using EXCEPTION block in the program and an appropriate action is taken against the
error condition. There are two types of exceptions −
 System-defined exceptions
 User-defined exceptions
Syntax for Exception Handling
The general syntax for exception handling is as follows. Here you can list down as many exceptions as
you can handle. The default exception will be handled using WHEN others THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had created
and used in the previous chapters −
DECLARE
c_id customers.id%type := 8;
c_name customerS.No.ame%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
59

END;
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!

PL/SQL procedure successfully completed.


The above program displays the name and address of a customer whose ID is given. Since there is no
customer with ID value 8 in our database, the program raises the run-time
exception NO_DATA_FOUND, which is captured in the EXCEPTION block.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal database error,
but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is
the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-defined exception. In
the next section, we will give you an example on raising a user-defined exception. You can raise the
Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-
defined exception must be declared and then raised explicitly, using either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID, when the user
enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.No.ame%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
60

WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;

EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.


Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated
by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT
INTO statement returns no rows. The following table lists few of the important pre-defined exceptions −
Oracle
Exception SQLCODE Description
Error

It is raised when a null object is


ACCESS_INTO_NULL 06530 -6530
automatically assigned a value.

It is raised when none of the choices in the


CASE_NOT_FOUND 06592 -6592 WHEN clause of a CASE statement is
selected, and there is no ELSE clause.

It is raised when a program attempts to


apply collection methods other than
EXISTS to an uninitialized nested table or
COLLECTION_IS_NULL 06531 -6531
varray, or the program attempts to assign
values to the elements of an uninitialized
nested table or varray.

It is raised when duplicate values are


DUP_VAL_ON_INDEX 00001 -1 attempted to be stored in a column with
unique index.

It is raised when attempts are made to make


INVALID_CURSOR 01001 -1001 a cursor operation that is not allowed, such
as closing an unopened cursor.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
61

It is raised when the conversion of a


INVALID_NUMBER 01722 -1722 character string into a number fails because
the string does not represent a valid number.

It is raised when a program attempts to log


LOGIN_DENIED 01017 -1017 on to the database with an invalid username
or password.

It is raised when a SELECT INTO


NO_DATA_FOUND 01403 +100
statement returns no rows.

It is raised when a database call is issued


NOT_LOGGED_ON 01012 -1012
without being connected to the database.

It is raised when PL/SQL has an internal


PROGRAM_ERROR 06501 -6501
problem.

It is raised when a cursor fetches value in a


ROWTYPE_MISMATCH 06504 -6504
variable having incompatible data type.

It is raised when a member method is


SELF_IS_NULL 30625 -30625 invoked, but the instance of the object type
was not initialized.

It is raised when PL/SQL ran out of


STORAGE_ERROR 06500 -6500
memory or memory was corrupted.

It is raised when a SELECT INTO


TOO_MANY_ROWS 01422 -1422
statement returns more than one row.

It is raised when an arithmetic, conversion,


VALUE_ERROR 06502 -6502
truncation, or sizeconstraint error occurs.

It is raised when an attempt is made to


ZERO_DIVIDE 01476 1476
divide a number by zero.

Program:
DECLARE
Roll_No NUMBER;
BookName varchar2(50);
IssueDate DATE;
CurrentDate DATE;
NoOfDays Number(2);
Fine Number;
BEGIN
DBMS_OUTPUT.PUT_LINE('Enter Student Roll Number');
Roll_No := &rollno;
DBMS_OUTPUT.PUT_LINE('Enter Book Name');
BookName := &bookname;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
62

CurrentDate := trunc(SYSDATE);
SELECT DateOfIssue into IssueDate FROM Borrower WHERE RollNo = Roll_No AND NameOfBook
=BookName;
SELECT trunc(SYSDATE) - IssueDate INTO NoOfDays from dual;
DBMS_OUTPUT.PUT_LINE('No of Days' || NoOfDays);
IF (NoOfDays > 30) THEN
Fine := NoOfDays * 50;
ELSIF (NoOfDays >= 15 AND NoOfDays <=30) THEN
Fine := NoOfDays * 5;
END IF;
IF FINE > 0 THEN
INSERT INTO Fine values (Roll_No, CurrentDate, Fine);
END IF;
UPDATE Borrower SET Status = 'R' WHERE RollNo=Roll_No;
END;

/*
Assignment No. A5
Roll No.:
Full Name:
Title: Unnamed PL/SQL code block: Use of Control structure and Exception handling is mandatory.
Write a PL/SQL block of code for the following requirements:-
Schema:
1. Borrower (Rollin, Name, DateofIssue, NameofBook, Status)
2. Fine (Roll_no,Date,Amt)
1. Accept roll_no & name of book from user.
2. Check the number of days (from date of issue), if days are between 15 to 30 then fine amount will
be Rs 5per day.
3. If no. of days>30, per day fine will be Rs 50 per day & for days less than 30, Rs. 5 per day.
4. After submitting the book, status will change from I to R.
5. If condition of fine is true, then details will be stored into fine table.
*/

<Your program here>

/* Output:
(As displayed after execution of above program.)
*/

Conclusion: Thus we have studied how to write pl/sql code block with the help of control structures and
exception handling.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
63

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

Problem Statement / Aim: Study of unnamed PL/SQL code block using parameterized Cursor and
Ability to write PL/SQL block of code using all types of cursors (Implicit, Explicit, Cursor FOR Loop,
Parameterized Cursor)

Theory:

Oracle creates a memory area, known as the context area, for processing an SQL statement, which
contains all the information needed for processing the statement; for example, the number of rows
processed, etc.

A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor
holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to
as the active set.

You can name a cursor so that it could be referred to in a program to fetch and process the rows returned
by the SQL statement, one at a time. There are two types of cursors −

 Implicit cursors
 Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there
is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be affected.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has
attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has
additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with
the FORALL statement. The following table provides the description of the most used attributes −

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
64

S.No Attribute & Description

%FOUND
1
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.

%NOTFOUND

2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE


statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.

%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.

%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example.

Example
We will be using the CUSTOMERS table we had created and used in the previous chapters.

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
65

+----+----------+-----+-----------+----------+

The following program will update the table and increase the salary of each customer by 500 and use
the SQL%ROWCOUNT attribute to determine the number of rows affected −

DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

6 customers selected

PL/SQL procedure successfully completed.

If you check the records in customers table, you will find that the rows have been updated −

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

Explicit Cursors

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
66

Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.

The syntax for creating an explicit cursor is −

CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory
Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT statement. For example

CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned
by the SQL statement into it. For example, we will open the above defined cursor as follows −

OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the
above-opened cursor as follows −

FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will close the above-opened
cursor as follows −

CLOSE c_customers;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
67

Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;

DECLARE
c_id customers.id%type;
c_name customerS.No.ame%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
68

Program:

1. IMPLICIT CURSOR EXAMPLE

SET SERVEROUTPUT ON;


BEGIN
UPDATE N_ROLLCALL SET ATTENDANCE='ABSENT' WHERE NAME='HENRY';
IF SQL%FOUND THEN
dbms_output.put_line('Updated - If Found');
END IF;
IF SQL%NOTFOUND THEN
dbms_output.put_line('NOT Updated - If NOT Found');
END IF;
IF SQL%ROWCOUNT>0 THEN
dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated');
ELSE
dbms_output.put_line('NO Rows Updated Found');
END IF;
END;
2. EXPLICIT CURSOR – EXAMPLE
SET SERVEROUTPUT ON;
DECLARE
CURSOR EXPLICIT_CUR IS select ROLLNO,NAME,ATT_DATE from N_ROLLCALL where
ATTENDANCE='ABSENT';
tmp EXPLICIT_CUR %rowtype;
BEGIN
OPEN EXPLICIT_CUR;
Loop exit when EXPLICIT_CUR%NOTFOUND;
FETCH EXPLICIT_CUR into tmp;
dbms_output.put_line('ROLL NO :' || tmp.ROLLNO || 'NAME : ' || tmp.NAME || 'DATE :' || tmp.ATT_DATE);
END Loop;
IF EXPLICIT_CUR%ROWCOUNT>0 THEN

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
69

dbms_output.put_line(SQL%ROWCOUNT||' ROWS FOUND');


ELSE
dbms_output.put_line('NO ROWS FOUND');
END IF;
CLOSE EXPLICIT_CUR;
END;
3. FOR LOOP CURSOR
SET SERVEROUTPUT ON;
DECLARE
cursor FOR_CUR is select ROLLNO,NAME,ATT_DATE from N_ROLLCALL where
ATTENDANCE='ABSENT';
tmp FOR_CUR %rowtype;
BEGIN
FOR tmp IN FOR_CUR
LOOP
dbms_output.put_line('ROLL NO :' || tmp.ROLLNO ||' '|| 'NAME : ' || tmp.NAME ||' '|| 'DATE :' || tmp.ATT_DATE);
END Loop;
END;
4. PROBLEM STATEMENT:- MERGE THE DATA AVAILABLE IN THE NEWLY CREATED TABLE
N_ROLLCALL WITH THE DATA AVAILABLE IN THE TABLE O_ROLLCALL
BEGIN
MERGE INTO N_ROLLCALL T1 USING (SELECT ROLLNO, NAME, ATT_DATE, ATTENDANCE FROM
O_ROLLCALL)T2 ON (T1.ROLLNO = T2.ROLLNO) WHEN NOT MATCHED THEN INSERT VALUES
(T2.ROLLNO,T2.NAME,T2.ATT_DATE,T2.ATTENDANCE);
IF SQL%FOUND THEN
dbms_output.put_line('MERGED');
END IF;
IF SQL%NOTFOUND THEN
dbms_output.put_line('NOT MERGED');
END IF;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
70

IF SQL%ROWCOUNT>0 THEN
dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated');
ELSE
dbms_output.put_line('NO Rows Updated Found');
END IF;
END;
5. PARAMETEREZIED CURSOR
DECLARE
CURSOR PARAM_CURSOR (ROLL NUMBER) IS SELECT * FROM N_ROLLCALL
WHERE ROLLNO = ROLL;
TMP PARAM_CURSOR %ROWTYPE;
BEGIN
FOR TMP IN PARAM_CURSOR (101) LOOP
dbms_output.put_line('NAME '||TMP.NAME);
dbms_output.put_line('DATE '||TMP.ATT_DATE);
dbms_output.put_line('ATTENDANCE: '||TMP.ATTENDANCE);
END Loop;
END;

/*
Assignment No. A6
Roll No.:
Full Name:
Title: Write a PL/SQL block of code using parameterized Cursor, that will merge the data available in
the newly created table N_RollCall with the data available in the table O_RollCall. If the data in the first
table already exist in the second table then that data should be skipped.
*/
<Your program here>

/* Output:
(As displayed after execution of above program.)
*/

Conclusion: Thus we have studied all types of cursors in pl/sql

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
71

Assignment No. A7
Title: 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 marks 899 and 825 category is Higher Second Class
Write a PL/SQL block for using procedure created with above requirement.

Problem Statement / Aim: Study of Stored Procedure & Stored Function

Theory:

Stored Procedures

What is a Stored Procedure?


A stored procedure or in simple a proc is a named PL/SQL block which performs one or more
specific task. This is similar to a procedure in other programming languages. A procedure has a header
and a body. The header consists of the name of the procedure and the parameters or variables passed to
the procedure. The body consists or declaration section, execution section and exception section similar
to a general PL/SQL Block.A 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 section
BEGIN
Execution section
EXCEPTION
Exception section
END;
IS - marks the beginning of the body of the procedure and is similar to DECLARE in
anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR
REPLACE together the procedure is created if no other procedure with the same name exists or the
existing procedure is replaced with the current code.

Procedures: Example
The below example creates a procedure ‘employer_details’ which gives the details of the employee.

CREATE OR REPLACE PROCEDURE employer_details

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
72

IS
CURSOR emp_cur IS
SELECT first_name, last_name, salary FROM emp_tbl;
emp_rec emp_cur%rowtype;
BEGIN
FOR emp_rec in sales_cur
LOOP
dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
|| ' ' ||emp_cur.salary);
END LOOP;
END;
/
How to execute a Stored Procedure?
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;
NOTE: In the examples given above, we are using backward slash ‘/’ at the end of the
program. This indicates the oracle engine that the PL/SQL program has ended and it can begin
processing the statements.

The following is a simple example of a procedure:


CREATE OR REPLACE Procedure UpdateCourse
( name_in IN varchar2 )

IS
cnumber number;

cursor c1 is
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;
end if;

INSERT INTO student_courses


( course_name,
course_number )
VALUES
( name_in,

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
73

cnumber );

commit;

close c1;

EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
END;

This procedure is called UpdateCourse. It has one parameter called name_in. The procedure
will lookup the course_number based on course name. If it does not find a match, it defaults the
course number to 99999. It then inserts a new record into the student_courses table.

Drop Procedure

Once you have created your procedure in Oracle, you might find that you need to remove it
from the database.
Syntax
The syntax to a drop a procedure in Oracle is:

DROP PROCEDURE procedure_name;

procedure_name
The name of the procedure that you wish to drop.

Example
Let's look at an example of how to drop a procedure in Oracle.
For example:
DROP PROCEDURE UpdateCourse;
This example would drop the procedure called UpdateCourse.

PL/SQL Functions
What is a Function in PL/SQL?

A function is a named PL/SQL Block which is similar to a procedure. The major difference between a
procedure and 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

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
74

BEGIN
Execution_section
Return return_variable;
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 any of 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
the header section.

For example, let’s create a frunction called ''employer_details_func' similar to the one created in
stored proc

CREATE OR REPLACE FUNCTION employer_details_func


RETURN VARCHAR(20);
IS
emp_name VARCHAR(20);
BEGIN
SELECT first_name INTO emp_name
FROM emp_tbl WHERE empID = '100';
RETURN emp_name;
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.

How to execute a PL/SQL Function?

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 of the function to it.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
75

2) As a part of a SELECT statement

SELECT employer_details_func FROM dual;

3) In a PL/SQL Statements like,

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

Program:
CREATE OR REPLACE PROCEDURE PROCEDURE_GRADE IS
Roll Number;
Stu_Name varchar(50);
Marks Number;
CURSOR Cursor1 IS
SELECT RollNo,Name,Total_Marks FROM Stud_Marks;
Stud_rec Cursor1%rowtype;
BEGIN
OPEN Cursor1;
LOOP
FETCH Cursor1 INTO Roll,Stu_Name,Marks;
EXIT WHEN Cursor1%notfound;
IF (Marks >= 990 AND Marks <= 1500) THEN
INSERT INTO Result values(ROLL, Stu_Name, 'DISTINCTION');
ELSIF (Marks >= 900 AND Marks <= 989) THEN
INSERT INTO REsult Values(ROLL,Stu_Name,'FIRST CLASS');
ELSIF (Marks >=825 AND Marks <=899) THEN
INSERT INTO Result Values(ROLL,Stu_Name,'SECOND CLASS');
END IF;
END LOOP;
CLOSE Cursor1;
END;

/*
Assignment No. A6
Roll No.:
Full Name:
Title: Write a PL/SQL block of code using parameterized Cursor, that will merge the data available in
the newly created table N_RollCall with the data available in the table O_RollCall. If the data in the first
table already exist in the second table then that data should be skipped.
*/
<Your program here>

/* Output:
(As displayed after execution of above program.)
*/
Conclusion: Thus have successfully studied and implemented stored procedure and function in
PL/SQL.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
76

Assignment No. A8
Title: Database Trigger (All Types: Row level and Statement level triggers, Before and After
Triggers). 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.

Problem Statement / Aim: Study of All Types: Row level and Statement level triggers, before
and After Triggers

Theory:

What is a Trigger?

A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is
executed on a database table. A trigger is triggered automatically when an associated DML statement is
executed.

Syntax of Triggers

Syntax for Creating a Trigger

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;

 CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given
name or overwrites an existing trigger with the same name.
 {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger get
fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on
a view. before and after cannot be used to create a trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More
than one triggering events can be used together separated by OR keyword. The trigger gets fired
at all the specified triggering event.
 [OF col_name] - This clause is used with update triggers. This clause is used when you want to
trigger an event only when a specific column is updated.
 CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given
name or overwrites an existing trigger with the same name.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
77

 [ON table_name] - This clause identifies the name of the table or view to which the trigger is
associated.
 [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new values
of the data being changed. By default, you reference the values as :old.column_name or
:new.column_name. The reference names can also be changed from old (or new) to any other
user-defined name. You cannot reference old values when inserting a record, or new values when
deleting a record, because they do not exist.
 [FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each row
gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is
executed(i.e.statement level Trigger).
 WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for
rows that satisfy the condition specified.

For Example: The price of a product changes constantly. It is important to maintain the history of the
prices of the products.

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),
product_name varchar2(32),
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.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
78

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 table is
also rolled back.

Types of PL/SQL Triggers

There are two types of triggers based on the which level it is triggered.
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

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
UPDATE ON product

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
79

FOR EACH ROW


BEGIN
INSERT INTO product_check
Values('Before update row level',sysdate);
END;
/

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 level 26-Nov-2008


Before update, row level 26-Nov-2008
After update, Row level 26-Nov-2008

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
80

Before update, row level 26-Nov-2008


After update, Row level 26-Nov-2008
After update, statement level 26-Nov-2008

The above result shows 'before update' and 'after update' row level events have occured twice, since two
records were updated. But 'before update' and 'after update' statement level events are fired only once per
sql statement.

Program:

SQL> create table LIBRARY_AUDIT_STMT_LVL(STMT_TYPE varchar(20),UPDATE_TS


timestamp);

Table created.

SQL> CREATE OR REPLACE TRIGGER TRIGGER_STMT_LVL_BEFORE_DELETE BEFORE


DELETE ON LIBRARY_AUDIT_STMT_LVL
2 BEGIN
3 INSERT INTO LIBRARY_AUDIT_STMT_LVL (STMT_TYPE, UPDATE_TS) VALUES
('BEFORE DELETE', CURRENT_TIMESTAMP);
4 END;
5 /

Trigger created.

SQL> CREATE OR REPLACE TRIGGER TRIGGER_STMT_LVL_AFTER_DELETE AFTER


DELETE ON LIBRARY_AUDIT_STMT_LVL
2 BEGIN
3 INSERT INTO LIBRARY_AUDIT_STMT_LVL(STMT_TYPE, UPDATE_TS) VALUES('AFTER
DELETE', CURRENT_TIMESTAMP);
4 END;
5 /

Trigger created.

SQL> select * from LIBRARY_AUDIT_STMT_LVL;

no rows selected

SQL> create table LIBRARY(BOOK_STATUS_ID NUMBER,BOOKNAME VARCHAR(20));

Table created.

SQL> INSERT INTO LIBRARY VALUES(11,'DBMS');

1 row created.

SQL> INSERT INTO LIBRARY VALUES(22,'JAVA');

1 row created.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
81

SQL> SELECT * FROM LIBRARY;

BOOK_STATUS_ID BOOKNAME
-------------- --------------------
11 DBMS
22 JAVA

SQL> DROP TRIGGER TRIGGER_STMT_LVL_AFTER_DELETE;

Trigger dropped.

SQL> CREATE OR REPLACE TRIGGER TRIGGER_STMT_LVL_AFTER_DELETE AFTER


DELETE ON LIBRARY
2 BEGIN
3 INSERT INTO LIBRARY_AUDIT_STMT_LVL(STMT_TYPE, UPDATE_TS) VALUES('AFTER
DELETE', CURRENT_TIMESTAMP);
4 END;
5 /

Trigger created.

SQL> DELETE FROM LIBRARY WHERE BOOK_STATUS_ID=22;

1 row deleted.

SQL> SELECT * FROM LIBRARY_AUDIT_STMT_LVL;

STMT_TYPE
--------------------
UPDATE_TS
----------------------------------------------------------------------
AFTER DELETE
31-AUG-17 05.13.44.843418 PM

SQL> DROP TRIGGER TRIGGER_STMT_LVL_BEFORE_DELETE;

Trigger dropped.

SQL> CREATE OR REPLACE TRIGGER TRIGGER_STMT_LVL_BEFORE_DELETE BEFORE


DELETE ON LIBRARY BEGIN
2 INSERT INTO LIBRARY_AUDIT_STMT_LVL (STMT_TYPE, UPDATE_TS) VALUES
('BEFORE DELETE', CURRENT_TIMESTAMP);
3 END;
4 /

Trigger created.

SQL> DELETE FROM LIBRARY WHERE BOOK_STATUS_ID=11;

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
82

1 row deleted.

SQL> SELECT * FROM LIBRARY_AUDIT_STMT_LVL;

STMT_TYPE
--------------------
UPDATE_TS
----------------------------------------------------------------------
AFTER DELETE
31-AUG-17 05.13.44.843418 PM

AFTER DELETE
31-AUG-17 05.20.54.175978 PM

BEFORE DELETE
31-AUG-17 05.24.25.852613 PM

STMT_TYPE
--------------------
UPDATE_TS
----------------------------------------------------------------------
AFTER DELETE
31-AUG-17 05.24.25.852880 PM

SQL> CREATE OR REPLACE TRIGGER TRIGGER_STMT_LVL_BEFORE_DELETE BEFORE


DELETE ON LIBRARY_AUDIT_STMT_LVL
2 BEGIN
3 INSERT INTO LIBRARY_AUDIT_STMT_LVL (STMT_TYPE, UPDATE_TS) VALUES
('BEFORE DELETE'SQL> , CURRENT_TIMESTAMP);
4 END;
5 /

Trigger created.

SQL> CREATE OR REPLACE TRIGGER TRIGGER_STMT_LVL_AFTER_DELETE AFTER


DELETE ON LIBRARY_AUDIT_STMT_LVL
2 BEGIN
3 INSERT INTO LIBRARY_AUDIT_STMT_LVL(STMT_TYPE, UPDATE_TS) VALUES('AFTER
DELESQL> TE', CURRENT_TIMESTAMP);
4 END;
5 /

Trigger created.

SQL> select * from LIBRARY_AUDIT_STMT_LVL;

no rows selected

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
83

SQL> create table LIBRARY(BOOK_STATUS_ID NUMBER,BOOKNAME VARCHAR(20));

Table created.

SQL> INSERT INTO LIBRARY VALUESQL> S(11,'DBMS');

1 row created.

SQL> INSERT INTO LIBRARY VALUES(22,'JAVA');

1 row created.

SQL> SELECT * FROM LIBRARY;

BOOK_STATUS_ID BOOKNAME
-------------- --------------------
11 DBMS
22 JAVA

SQL> DROP TRIGGER TRIGGER_STMT_LVL_AFTER_DELETE;

Trigger dropped.

SQL> CREATE OR REPLACE TRIGGER TRIGGER_STMT_LVL_AFTER_DELETE AFTER


DELETE ON LIBRARY
2 BEGIN 5
3 INSERT INTO LIBRARY_AUDIT_STMT_LVL(STMT_TYPE, UPDATE_TS) VALUES('AFTER
DELETE', CURRENT_TIMESTAMP);
4 END;
5 /

Trigger created. 6 7 8 9 10 11 12 13

SQL> DELETE FROM LIBRARY WHERE BOOK_STATUS_ID=22;

1 row deleted.

SQL> SELECT * FROM LIBRARY_AUDIT_STMT_LVL;

STMT_TYPE
--------------------
UPDATE_TS
---------------------------------------------------------------------------
AFTER DELET 14 E
31-AUG-17 05.13.44.843418 PM

SQL> DROP TRIGGER TRIGGER_STMT_LVL_BEFORE_DELETE;

Trigger dropped.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
84

SQL> DELETE 15 FROM LIBRARY WHERE BOOK_STATUS_ID 16 = 17 1 18 1;

1 row deleted.

SQL> SELECT * FROM LIBRARY_AUDIT_STMT_LVL;

STMT_TYPE
--------------------
UPDATE_TS 19
---------- 20 -----------------------------------------------------------------
AFTER DELETE
31-AUG-17 05.13.44.843418 PM
21
AFTER DEL 22 ETE
31- 23 AUG-17 05.20.54.175978 PM

SQL> INSERT INTO LIBRARY VALUES(11,'DBMS');

1 row created.

SQL> CREAT 24 E OR REPLACE TRIGGER TRIGGER 25 _STMT_LVL_BEFORE_ 26 DELETE


BEFORE DELETE ON LIBRARY BE 27 G 28 I 29 N
2 INSERT INTO LIBRARY_AUDIT_STMT_LVL (STMT_TYPE, UPDATE_TS) VALUES
('BEFORE DELETE', CURRENT_TIMESTA 30 MP);
31 3 END;
4 /

Trigger created.

SQL> DELETE FROM LIBRARY WHERE BOOK_STATUS_ID=11;

1 row deleted.

SQL> SE 32 LECT * FRO 33 M LIBRA 34 RY_AUDIT_STMT_LVL;

STMT_TYPE
--------------------
UPDATE_TS
--------------------------------------- 35 -------------------------
AFTER DELETE
31-AUG-17 05.13.44.843418 PM

AFTER DELETE
31-AUG 36 -17 05.20.54.1759 37 78 PM

BEFORE DELETE
31-AUG-17 05.24.25.8 38 5 39 2 40 613 PM

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
85

STMT_TYPE
--------------------
UPDATE_TS
---------------------------------------- 41 ----------- 42 ---------
AFTER DELETE
31-AUG-17 05.24.25.852880 PM

/*
Assignment No. A8
Roll No.:
Full Name:
Title: Database Trigger (All Types: Row level and Statement level triggers, Before and After
Triggers). 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.

*/
<Your program here>

/* Output:
(As displayed after execution of above program.)
*/
Conclusion: Thus have successfully studied and implemented All Types: Row level and
Statement level triggers, before and After Triggers

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
86

Assignment No. B1
Title: Study of Open Source NOSQL Database: MongoDB (Installation, Basic CRUD operations,
Execution)

Problem Statement / Aim: Upon Completion of this assignment students should able to learn

1. Install MongoDB

2. Execute simple MongoDB Commands.

3. Study NoSQL database.

4. Study documented oriented database-Mongodb.

Theory:
1. What is MongoDB?

 MongoDB is an open-source document database that provides high performance,


high availability, and automatic scaling.
 A record in MongoDB is a document, which is a data structure composed of field and
value pairs.
 MongoDB documents are BSON documents. BSON is a binary representation of JSON
with additional type information.
 A document is the basic unit of data for MongoDB and is roughly equivalent to a row
in a relational database management system.
 A collection is a group of documents. If a document is the MongoDB analog of a row
in a relational database, then a collection are analog to a table.
 MongoDB is type-sensitive and case-sensitive.
 Every document has a special key, "_id", that is unique within a collection.
In the documents, the value of a field can be any of the BSON data types, including
other documents, arrays, and arrays of documents.

Name: “Sagar”,

Class: “TE Comp”,

College: “MESCOE”,

Age: 26,

Subject: [“DMSA”, “OSD”, “FCA”, “DCWSN”, “TOC”]

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
87

Install MongoDB on Fedora

Step #1: Add the MongoDB Repository

vi /etc/yum.repos.d/mongodb.repo

Option A: If you are running a 64-bit system, add the following information to the file you’ve
created, using i to insert:

[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1

Then exit and save the file with the command :wq .

Option B: If you are running a 32-bit system, add the following information to the file you’ve
created, using i to insert:

[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/i686/
gpgcheck=0
enabled=1

Then exit and save the file with the command :wq .

Step #2: Install MongoDB

Then run following command:

yum -y install mongodb-org mongodb-org-server

Step #3: Get MongoDB Running

systemctl start mongod

Enter the MongoDB Command Line

Mongo

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
88

/*
Assignment No. B1
Roll No.:
Full Name:
Title: Study of Open Source NOSQL Database: MongoDB (Installation, Basic CRUD operations,
Execution)

*/
<Your program here>

/* Output:
(As displayed after execution of above program.)
*/
Conclusion: Here we performed installation of mongoDB

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
89

Assignment No. B2
Title: Design and Develop MongoDB Queries using CRUD operations. (Use CRUD operations,
SAVE method, logical operators)

Problem Statement / Aim: Upon Completion of this assignment students should able to learn
1. Execute simple MongoDB Commands.

2. Execute simple MongoDB CRUD operation.

3. Study logical operators in MongoDB.

Theory:

CRUD Operations in MongoDB:

CRUD operations refer to the basic Insert, Read, Update and Delete operations. CRUD

stands for create, read, update, and delete. These terms are the foundation for all

interactions with the database.

2. MongoDB Create Database

The use Command

MongoDB use DATABASE_NAME is used to create database. The command will

create a new database; if it doesn't exist otherwise it will return the existing database.

Syntax: >use DATABASE_NAME

Example: >use mydb

switched to db mydb

To check your currently selected database uses the command db.

>db

mydb

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
90

If you want to check your databases list, then use the command show dbs.

>show dbs

local 0.78125GB

test 0.23012GB

Your created database (mydb) is not present in list. To display database you need to

insert atleast one document into it.

In mongodb default database is test. If you didn't create any database then collections

will be stored in test database

3. MongoDB Drop Database

The dropDatabase () Method

MongoDB db.dropDatabase () command is used to drop a existing database.

Syntax: db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database.

4. MongoDB Create Collection

The createCollection() Method

MongoDB db.createCollection(name, options) is used to create collection. In the command,


name is name of collection to be created. Options are a document and used to specify
configuration of collection. Options parameter is optional, so you need to specify only name
of the collection.

Syntax: db.createCollection(name, options)

Examples: Basic syntax of createCollection() method without options is as follows:

>use test

switched to db test

>db.createCollection("mycollection")
Department of Computer Engineering Dr D Y Patil School of Engineering
Lohegaon, Pune – 412 105
91

{ "ok" : 1 }

5. MongoDB Drop Collection

The drop() Method

MongoDB's db.collection.drop() is used to drop a collection from the database.

Syntax: db.COLLECTION_NAME.drop()

6. MongoDB - Insert Document

The insert() Method

To insert data into MongoDB collection, you need to use MongoDB's insert() , update() or
save () method.

Syntax: db.COLLECTION_NAME.insert(document)

7. MongoDB - Query Document

The find() Method

To query data from MongoDB collection, you need to use MongoDB's find() method.

Find() method will display all the documents in a non-structured way.

Syntax: db.COLLECTION_NAME.find()

The pretty() Method

To display the results in a formatted way, you can use pretty() method.

Syntax: db.COLLECTION_NAME.find().pretty()

The forEach() Method

To display the results in a JSON format, you can use forEach() method.

Syntax: db.COLLECTION_NAME.find().forEach(printjson)

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
92

8. MongoDB Update Document

MongoDB's update() and save() methods are used to update document into a collection.

The update() method update values in the existing document while the save() method

replaces the existing document with the document passed in save() method.

MongoDB Update() method

The update() method updates values in the existing document.

Syntax:

db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA,UPDATED_DATA)

MongoDB Save() Method

The save() method replaces the existing document with the new document passed in save()

method.

Syntax: db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

9. MongoDB Delete Document

The remove() Method

MongoDB's remove() method is used to remove document from the collection. remove()

method accepts two parameters. One is deletion criteria and second is justOne flag

1. Deletion criteria: (Optional) deletion criteria according to documents will be removed.

2. justOne: (Optional) if set to true or 1, then remove only one document.

Syntax: db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Logical Query Operators

Name Description

$and Joins query clauses with a logical AND returns all documents that match the conditions of both

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
93

Name Description

clauses.

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

$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

Program:

> show databases;


admin (empty)
local 0.078GB
test 0.078GB
> use DBMS
switched to db DBMS
> db.createCollection("test")
{ "ok" : 1 }
>
db.test.insert({name:"Arun",roll:1,class:"TE"},{name:"Akib",roll:2,cla
ss:"TE"},{name:"Pranav",roll:3,class:"TE"},{name:"Achyuth",roll:4,clas
s:"TE"},{name:"Yash",roll:5,class:"SE"},{name:"Sagar",roll:6,class:"BE
"},{name:"Adil",roll:7,class:"SE"},{name:"Shreyas",roll:8,class:"BE"})
WriteResult({ "nInserted" : 1 })
> db.test.find().pretty()
{
"_id" : ObjectId("561265687d597a0aecab9241"),
"name" : "Arun",
"roll" : 1,
"class" : "TE"
}
>
db.test.insert([{name:"Akib",roll:2,class:"TE"},{name:"Pranav",roll:3,
class:"TE"},{name:"Achyuth",roll:4,class:"TE"},{name:"Yash",roll:5,cla
ss:"SE"},{name:"Sagar",roll:6,class:"BE"},{name:"Adil",roll:7,class:"S
E"},{name:"Shreyas",roll:8,class:"BE"}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
94

"nInserted" : 7,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.test.find().pretty()
{
"_id" : ObjectId("561265687d597a0aecab9241"),
"name" : "Arun",
"roll" : 1,
"class" : "TE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9242"),
"name" : "Akib",
"roll" : 2,
"class" : "TE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9243"),
"name" : "Pranav",
"roll" : 3,
"class" : "TE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9244"),
"name" : "Achyuth",
"roll" : 4,
"class" : "TE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9245"),
"name" : "Yash",
"roll" : 5,
"class" : "SE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9246"),
"name" : "Sagar",
"roll" : 6,
"class" : "BE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9247"),
"name" : "Adil",
"roll" : 7,
"class" : "SE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9248"),

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
95

"name" : "Shreyas",
"roll" : 8,
"class" : "BE"
}
> db.test.find({name:"Arun"})
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun",
"roll" : 1, "class" : "TE" }
> db.test.find({name:"Arun"}).pretty()
{
"_id" : ObjectId("561265687d597a0aecab9241"),
"name" : "Arun",
"roll" : 1,
"class" : "TE"
}
> db.test.find({},{name:"Arun"}).pretty()
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun" }
{ "_id" : ObjectId("561265f77d597a0aecab9242"), "name" : "Akib" }
{ "_id" : ObjectId("561265f77d597a0aecab9243"), "name" : "Pranav" }
{ "_id" : ObjectId("561265f77d597a0aecab9244"), "name" : "Achyuth" }
{ "_id" : ObjectId("561265f77d597a0aecab9245"), "name" : "Yash" }
{ "_id" : ObjectId("561265f77d597a0aecab9246"), "name" : "Sagar" }
{ "_id" : ObjectId("561265f77d597a0aecab9247"), "name" : "Adil" }
{ "_id" : ObjectId("561265f77d597a0aecab9248"), "name" : "Shreyas" }
> db.test.find({},{name:0}).pretty()
{ "_id" : ObjectId("561265687d597a0aecab9241"), "roll" : 1, "class" :
"TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9242"), "roll" : 2, "class" :
"TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9243"), "roll" : 3, "class" :
"TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9244"), "roll" : 4, "class" :
"TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9245"), "roll" : 5, "class" :
"SE" }
{ "_id" : ObjectId("561265f77d597a0aecab9246"), "roll" : 6, "class" :
"BE" }
{ "_id" : ObjectId("561265f77d597a0aecab9247"), "roll" : 7, "class" :
"SE" }
{ "_id" : ObjectId("561265f77d597a0aecab9248"), "roll" : 8, "class" :
"BE" }
> db.test.find({},{name:1}).pretty()
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun" }
{ "_id" : ObjectId("561265f77d597a0aecab9242"), "name" : "Akib" }
{ "_id" : ObjectId("561265f77d597a0aecab9243"), "name" : "Pranav" }
{ "_id" : ObjectId("561265f77d597a0aecab9244"), "name" : "Achyuth" }
{ "_id" : ObjectId("561265f77d597a0aecab9245"), "name" : "Yash" }
{ "_id" : ObjectId("561265f77d597a0aecab9246"), "name" : "Sagar" }
{ "_id" : ObjectId("561265f77d597a0aecab9247"), "name" : "Adil" }
{ "_id" : ObjectId("561265f77d597a0aecab9248"), "name" : "Shreyas" }
> db.test.find({},{name:1,_id:0}).pretty()
{ "name" : "Arun" }
{ "name" : "Akib" }

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
96

{ "name" : "Pranav" }
{ "name" : "Achyuth" }
{ "name" : "Yash" }
{ "name" : "Sagar" }
{ "name" : "Adil" }
{ "name" : "Shreyas" }
> db.test.find({name:{$in:["Arun","Shreyas","Snehalata"]}})
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun",
"roll" : 1, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9248"), "name" : "Shreyas",
"roll" : 8, "class" : "BE" }
> db.test.find({name:{$in:["Arun","Shreyas","Snehalata"]}}).pretty()
{
"_id" : ObjectId("561265687d597a0aecab9241"),
"name" : "Arun",
"roll" : 1,
"class" : "TE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9248"),
"name" : "Shreyas",
"roll" : 8,
"class" : "BE"
}
> db.test.find({name:"Arun",roll:1})
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun",
"roll" : 1, "class" : "TE" }
> db.test.find({name:"Arun",roll:2})
> db.test.find({roll:{$lt:5}})
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun",
"roll" : 1, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9242"), "name" : "Akib",
"roll" : 2, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9243"), "name" : "Pranav",
"roll" : 3, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9244"), "name" : "Achyuth",
"roll" : 4, "class" : "TE" }
> db.test.find({roll:{$gt:5}})
{ "_id" : ObjectId("561265f77d597a0aecab9246"), "name" : "Sagar",
"roll" : 6, "class" : "BE" }
{ "_id" : ObjectId("561265f77d597a0aecab9247"), "name" : "Adil",
"roll" : 7, "class" : "SE" }
{ "_id" : ObjectId("561265f77d597a0aecab9248"), "name" : "Shreyas",
"roll" : 8, "class" : "BE" }
> db.test.find({roll:{$gte:5}})
{ "_id" : ObjectId("561265f77d597a0aecab9245"), "name" : "Yash",
"roll" : 5, "class" : "SE" }
{ "_id" : ObjectId("561265f77d597a0aecab9246"), "name" : "Sagar",
"roll" : 6, "class" : "BE" }
{ "_id" : ObjectId("561265f77d597a0aecab9247"), "name" : "Adil",
"roll" : 7, "class" : "SE" }

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
97

{ "_id" : ObjectId("561265f77d597a0aecab9248"), "name" : "Shreyas",


"roll" : 8, "class" : "BE" }
> db.test.find({roll:{$lte:5}})
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun",
"roll" : 1, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9242"), "name" : "Akib",
"roll" : 2, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9243"), "name" : "Pranav",
"roll" : 3, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9244"), "name" : "Achyuth",
"roll" : 4, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9245"), "name" : "Yash",
"roll" : 5, "class" : "SE" }
> db.test.find({$or:[{roll:{$gt:5}},{name:"Arun"}]})
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun",
"roll" : 1, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9246"), "name" : "Sagar",
"roll" : 6, "class" : "BE" }
{ "_id" : ObjectId("561265f77d597a0aecab9247"), "name" : "Adil",
"roll" : 7, "class" : "SE" }
{ "_id" : ObjectId("561265f77d597a0aecab9248"), "name" : "Shreyas",
"roll" : 8, "class" : "BE" }
> db.test.find({$or:[{roll:{$lt:4}},{roll:{$gt:6}}]})
{ "_id" : ObjectId("561265687d597a0aecab9241"), "name" : "Arun",
"roll" : 1, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9242"), "name" : "Akib",
"roll" : 2, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9243"), "name" : "Pranav",
"roll" : 3, "class" : "TE" }
{ "_id" : ObjectId("561265f77d597a0aecab9247"), "name" : "Adil",
"roll" : 7, "class" : "SE" }
{ "_id" : ObjectId("561265f77d597a0aecab9248"), "name" : "Shreyas",
"roll" : 8, "class" : "BE" }
> db.test.find({name:{$in:["Arun","Shreyas","Snehalata"]}}).pretty()
{
"_id" : ObjectId("561265687d597a0aecab9241"),
"name" : "Arun",
"roll" : 1,
"class" : "TE"
}
{
"_id" : ObjectId("561265f77d597a0aecab9248"),
"name" : "Shreyas",
"roll" : 8,
"class" : "BE"
}
> db.test.ensureIndex({"name":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
98

}
> db.test.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "DBMS.test"
},
{
"v" : 1,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "DBMS.test"
}
]
> db.test.ensureIndex({"roll":-1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
> db.test.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "DBMS.test"
},
{
"v" : 1,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "DBMS.test"
},
{
"v" : 1,
"key" : {
"roll" : -1
},
"name" : "roll_-1",
"ns" : "DBMS.test"

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
99

}
]
> db.test.dropIndex({"name":1})
{ "nIndexesWas" : 3, "ok" : 1 }
> db.test.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "DBMS.test"
},
{
"v" : 1,
"key" : {
"roll" : -1
},
"name" : "roll_-1",
"ns" : "DBMS.test"
}
]
> db.test.dropIndex({"roll":1})
{
"nIndexesWas" : 2,
"ok" : 0,
"errmsg" : "can't find index with key:{ roll: 1.0 }"
}
> db.test.dropIndex({"roll":-1})
{ "nIndexesWas" : 2, "ok" : 1 }

/*
Assignment No. B2
Roll No.:
Full Name:
Title: Design and Develop MongoDB Queries using CRUD operations. (Use CRUD operations,
SAVE method, logical operators)

*/
<Your program here>

/* Output:
(As displayed after execution of above program.)
*/
Conclusion: Here we performed CRUD operations of mongoDB

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
100

Assignment No. B3

Title: Aggregation and indexing with suitable example using MongoDB.

Problem Statement / Aim: Upon Completion of this assignment students should able to learn

1. Implement Aggregation operations using MongoDB

2. Implement indexing operations using MongoDB

Theory:

MongoDB Aggregation:

Aggregations operations process data records and return computed results.


Aggregation operations group values from multiple documents together, and can
perform a variety of operations on the grouped data to return a single result. In sql
count(*) and with group by is an equivalent of mongodb aggregation.

The aggregate() Method:

For the aggregation in mongodb you should use aggregate() method.


Syntax:

>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

There is a list available aggregation expressions:

Descriptio
Expression n Example

db.mycol.aggregate([{$grou
Sums up the defined p : {_id :

$sum value from all documents "$by_user", num_example : {$sum :

in the collection. "$likes"}}}])

Calculates the average of db.mycol.aggregate([{$grou


p : {_id :
all given values from all
$avg "$by_user", num_example : {$avg :

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
101

documents in the
"$likes"}}}])
collection.

Gets the minimum of the


db.mycol.aggregate([{$group : {_id :
corresponding values
$min "$by_user", num_example : {$min :
from all documents in the
"$likes"}}}])
collection.

Gets the maximum of the


db.mycol.aggregate([{$group : {_id :
corresponding values
$max "$by_user", num_example : {$max :
from all documents in the
"$likes"}}}])
collection.

Inserts the value to an


db.mycol.aggregate([{$group : {_id :
$push array in the resulting
"$by_user", url : {$push:
"$url"}}}])
document.

Inserts the value to an

array in the resulting db.mycol.aggregate([{$group : {_id :


$addToSet
document but does not "$by_user", url : {$addToSet : "$url"}}}])

create duplicates.

Gets the first document

from the source

document
s according to

$first the grouping. Typically db.mycol.aggregate([{$group : {_id :

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
102

this makes only sense "$by_user", first_url : {$first : "$url"}}}])

together with some

previously applied

“$sort”-stage.

Example:

In the collection you have the following data:

_id: ObjectId(7df78ad8902c)

title: 'MongoDB
Overview',

description: 'MongoDB is no sql database',

by_user: 'NileshKorade',

url:
'http://www.NileshKorade.com',

tags: ['mongodb', 'database',


'NoSQL'],

likes: 100

},

_id: ObjectId(7df78ad8902d)

title: 'NoSQL Overview',

description: 'No sql database is very fast',

by_user: 'NileshKorade',

url:
'http://www.NileshKorade.com',

tags: ['mongodb', 'database',


'NoSQL'],

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
103

likes: 10

},

_id: ObjectId(7df78ad8902e)

title: 'Neo4j
Overview',

description: 'Neo4j is no sql


database',

by_user: 'Neo4j',

url: 'http://www.neo4j.com', tags:


['neo4j', 'database', 'NoSQL'], likes:
750

},

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

examples are written by each user then you will use aggregate() method as shown

below:

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

Result: Out Put

"result" : [

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
104

"_id" : "NileshKorade",
"num_example" : 2

},

"_id" : "NileshKorade",
"num_example" : 1

],

"ok" : 1

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 require 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:

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

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
105

ensureIndex() method also accepts list of options (which are optional), whose
list is given below:

Parameter Type Description

Builds the index in the background so that building an


backgroun
Boolean index does not block other database activities. Specify true
d
to build in the background. The default value is false.

Creates a unique index so that the collection will not accept

insertion of documents where the index key or keys match


unique Boolean
an existing value in the index. Specify true to create a

unique index. The default value is false.

The name of the index. If unspecified, MongoDB generates

name string an index name by concatenating the names of the indexed

fields and the sort order.

Creates a unique index on a field that may have duplicates.

MongoDB indexes only the first occurrence of a key and

dropDups Boolean removes all documents from the collection that contain

subsequent occurrences of that key. Specify true to create

unique index. The default value is false.

If true, the index only references documents with the

specified field. These indexes use less space but behave


sparse Boolean
differently in some situations (particularly sorts). The

default value is false.

expireAfter Specifies a value, in seconds, as a TTL to control how long


integer
Seconds MongoDB retains documents in this collection.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
106

The index version number. The default index version


index
v depends on the version of mongod running when creating
version
the index.

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})

Program:

> use mongo


switched to db mongo
> db.employee.insert({'custID':'A123','Amount':500,'status':'A'})
WriteResult({ "nInserted" : 1 })
> db.employee.insert({'custID':'A123','Amount':250,'status':'A'})
WriteResult({ "nInserted" : 1 })
> db.employee.insert({'custID':'B212','Amount':200,'status':'A'})
WriteResult({ "nInserted" : 1 })
> db.employee.insert({'custID':'A123','Amount':300,'status':'D'})
WriteResult({ "nInserted" : 1 })
> db.employee.find().pretty()
{
"_id" : ObjectId("53d093599c406c0509bc5f89"),
"custID" : "A123",
"Amount" : 500,
"status" : "A"
}
{
"_id" : ObjectId("53d093829c406c0509bc5f8a"),
"custID" : "A123",
"Amount" : 250,
"status" : "A"
}
{
"_id" : ObjectId("53d093a69c406c0509bc5f8b"),
"custID" : "B212",
"Amount" : 200,
"status" : "A"

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
107

}
{
"_id" : ObjectId("53d093c49c406c0509bc5f8c"),
"custID" : "A123",
"Amount" : 300,
"status" : "D"
}

>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$sum:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 750 }
>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$min:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 250 }
>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$max:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 500 }
>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$max:'$Amount'}}}])

db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$status',
'totalAmount':{$sum:'$Amount'}}}])
{ "_id" : "A", "totalAmount" : 950 }
>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$avg:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 375 }
>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$avg:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 375 }
>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$first:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 500 }
>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$last:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 250 }

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
108

>
db.employee.aggregate([{$match:{'status':'A'}},{$group:{_id:'$custID',
'totalAmount':{$push:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : [ 200 ] }}

>
db.employee.aggregate([{$sort:{'custID':1}},{$group:{_id:'$custID','to
talAmount':{$sum:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 1050 }
>
db.employee.aggregate([{$sort:{'custID':1}},{$group:{_id:'$custID','to
talAmount':{$avg:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 350 }
>
db.employee.aggregate([{$sort:{'custID':1}},{$group:{_id:'$custID','to
talAmount':{$min:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 250 }
>
db.employee.aggregate([{$sort:{'custID':1}},{$group:{_id:'$custID','to
talAmount':{$max:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 500 }
>
db.employee.aggregate([{$sort:{'custID':1}},{$group:{_id:'$custID','to
talAmount':{$first:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 500 }
>
db.employee.aggregate([{$sort:{'custID':1}},{$group:{_id:'$custID','to
talAmount':{$last:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 300 }
>
db.employee.aggregate([{$sort:{'custID':1}},{$group:{_id:'$custID','to
talAmount':{$push:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : [ 200 ] }
{ "_id" : "A123", "totalAmount" : [ 500, 250, 300 ] }

> >
db.employee.aggregate([{$skip:1},{$group:{_id:'$custID','totalAmount':
{$sum:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 550 }
>
db.employee.aggregate([{$skip:1},{$group:{_id:'$custID','totalAmount':
{$avg:'$Amount'}}}])

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
109

{ "_id" : "B212", "totalAmount" : 200 }


{ "_id" : "A123", "totalAmount" : 275 }
>
db.employee.aggregate([{$skip:1},{$group:{_id:'$custID','totalAmount':
{$max:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 300 }
>
db.employee.aggregate([{$skip:1},{$group:{_id:'$custID','totalAmount':
{$min:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 250 }
>
db.employee.aggregate([{$skip:1},{$group:{_id:'$custID','totalAmount':
{$push:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : [ 200 ] }
{ "_id" : "A123", "totalAmount" : [ 250, 300 ] }
>
db.employee.aggregate([{$skip:1},{$group:{_id:'$custID','totalAmount':
{$first:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 250 }
>
db.employee.aggregate([{$skip:1},{$group:{_id:'$custID','totalAmount':
{$last:'$Amount'}}}])
{ "_id" : "B212", "totalAmount" : 200 }
{ "_id" : "A123", "totalAmount" : 300 }
>

>
db.employee.aggregate([{$limit:2},{$group:{_id:'$custID','totalAmount'
:{$sum:'$Amount'}}}])
{ "_id" : "A123", "totalAmount" : 750 }
>
db.employee.aggregate([{$limit:2},{$group:{_id:'$custID','totalAmount'
:{$avg:'$Amount'}}}])
{ "_id" : "A123", "totalAmount" : 375 }
>
db.employee.aggregate([{$limit:2},{$group:{_id:'$custID','totalAmount'
:{$min:'$Amount'}}}])
{ "_id" : "A123", "totalAmount" : 250 }
>
db.employee.aggregate([{$limit:2},{$group:{_id:'$custID','totalAmount'
:{$max:'$Amount'}}}])
{ "_id" : "A123", "totalAmount" : 500 }
>
db.employee.aggregate([{$limit:2},{$group:{_id:'$custID','totalAmount'
:{$first:'$Amount'}}}])
{ "_id" : "A123", "totalAmount" : 500 }

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
110

>
db.employee.aggregate([{$limit:2},{$group:{_id:'$custID','totalAmount'
:{$last:'$Amount'}}}])
{ "_id" : "A123", "totalAmount" : 250 }
>
db.employee.aggregate([{$limit:2},{$group:{_id:'$custID','totalAmount'
:push:'$Amount'}}}])
2014-07-24T11:38:07.873+0530 SyntaxError: Unexpected token :
>
db.employee.aggregate([{$limit:2},{$group:{_id:'$custID','totalAmount'
:{$push:'$Amount'}}}])
{ "_id" : "A123", "totalAmount" : [ 500, 250 ] }

/*
Assignment No. B3
Roll No.:
Full Name:
Title: Aggregation and indexing with suitable example using MongoDB.

*/
<Your program here>

/* Output:
(As displayed after execution of above program.)
*/
Conclusion: Here we performed Aggregation and indexing with suitable example using MongoDB.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
111

Assignment No. B4
Title: Implement Map reduces operation with suitable example using MongoDB.

Problem Statement / Aim: Upon Completion of this assignment students should able to learn
Implement Map reduces operations using MongoDB.

Theory:
MongoDB Map Reduce:

As per the MongoDB documentation, 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.

The map-reduce function first queries the collection, then maps the result
documents to emit key-value pairs which is then reduced based on the keys that have
multiple values.

 map is a javascript function that maps a value with a key and emits a key-
valur pair

 reduce is a javscript function that reduces or groups all the documents
having the same key

 out specifies the location of the map-reduce query result

 query specifies the optional selection criteria for selecting documents

 sort specifies the optional sort criteria

 limit specifies the optional maximum number of documents to be
returned

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
112

MapReduce Command:

Following is the 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

Example:

Consider the following document structure storing user posts. The document

stores user_name of the user and the status of post.

{"post_text": "NileshKorade is an awesome website for tutorials", "user_name": "mark",


"status":"active"

Now, we will use a mapReduce function on our posts collection to select all

The active posts, group them on the basis of user_name and then count the number

of posts by each user using the following code:

>db.posts.mapReduce(

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
113

function() { emit(this.user_id,1); },

function(key, values) {return Array.sum(values)},

{ query:{status:"active"}, out:"post_total"

})

Result:
{

"result" : "post_total",
"timeMillis" : 9, "counts"
:{

"input" : 4,
"emit" : 4,
"reduce" : 2,
"output" : 2

},

"ok" : 1,

The result shows that a total of 4 documents matched the query

(status:"active"), the map function emitted 4 documents with key-value pairs and

finally the reduce function grouped mapped documents having the same keys into

2. To see the result of this mapReduce query use the find operator:

>db.posts.mapReduce(

function() { emit(this.user_id,1); },

function(key, values) {return Array.sum(values)},

{query:{status:"active"}, out:"post_total"

}).find()

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
114

Result: The above query gives the following result which indicates that both users

tom and mark have two posts in active states:

{ "_id" : "tom", "value" : 2 } { "_id" : "mark", "value" : 2 }

Program:

> show databases;


admin (empty)
local 0.078GB
test 0.078GB
> use DBMS
switched to db DBMS
> db.createCollection("test")
{ "ok" : 1 }
>
db.test.insert({name:"Arun",roll:1,class:"TE"},{name:"Akib",roll:2,cla
ss:"TE"},{name:"Pranav",roll:3,class:"TE"},{name:"Achyuth",roll:4,clas
s:"TE"},{name:"Yash",roll:5,class:"SE"},{name:"Sagar",roll:6,class:"BE
"},{name:"Adil",roll:7,class:"SE"},{name:"Shreyas",roll:8,class:"BE"})
WriteResult({ "nInserted" : 1 })
> db.test.find().pretty()
{
"_id" : ObjectId("561265687d597a0aecab9241"),
"name" : "Arun",
"roll" : 1,
"class" : "TE"
}
>
db.test.insert([{name:"Akib",roll:2,class:"TE"},{name:"Pranav",roll:3,
class:"TE"},{name:"Achyuth",roll:4,class:"TE"},{name:"Yash",roll:5,cla
ss:"SE"},{name:"Sagar",roll:6,class:"BE"},{name:"Adil",roll:7,class:"S
E"},{name:"Shreyas",roll:8,class:"BE"}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 7,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> var Mapfunction = function(){emit(this.class,this.roll)}
> var Reducefunction = function(key,values){return Array.sum(values)}
> db.test.mapReduce(Mapfunction,Reducefunction,{'out':'resultant'})
{

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
115

"result" : "resultant",
"timeMillis" : 6,
"counts" : {
"input" : 8,
"emit" : 8,
"reduce" : 3,
"output" : 3
},
"ok" : 1,
}
> show collections
resultant
system.indexes
test
> db.resultant.find()
{ "_id" : "BE", "value" : 14 }
{ "_id" : "SE", "value" : 12 }
{ "_id" : "TE", "value" : 10 }

/*
Assignment No. B4
Roll No.:
Full Name:
Title: Implement Map reduces operation with suitable example using MongoDB.

*/
<Your program here>

/* Output:
(As displayed after execution of above program.)
*/
Conclusion: Here we performed Map reduce operation with suitable example using
MongoDB.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
116

Assignment No. B5

Title: Design and Implement any 5 query using MongoDB.

Problem Statement / Aim: Upon Completion of this assignment students should able to
learn Implement various queries using MongoDB

Theory:

MongoDB Commands: 1.
use Command:

MongoDB use DATABASE_NAME is used to create database. The command


will create a new database, if it doesn't exist otherwise it will return the existing
database.

Syntax:

use DATABASE_NAME

Example:

If you want to create a database with name <mydb>, then use DATABASE
statement would be as follows:

>use mydb

switched to db mydb

To check your currently selected database use the command db

>db

mydb

If you want to check your databases list, then use the command show dbs.

In mongodb default database is test. If you didn't create any database then
collections will be stored in test database.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
117

The dropDatabase() Method:

MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax:

db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database

The createCollection() Method:

MongoDB db.createCollection(name, options) is used to create collection.

Syntax:

db.createCollection(name, options)

Parameter Type Description

Name String Name of the collection to be created

Options Document (Optional) Specify options about memory size and indexing

Examples:

Basic syntax of createCollection() method without options is as follows

db.createCollection("mycollection")

{ "ok" : 1 }

You can check the created collection by using the command show collections

>show collections
mycollection

In mongodb you don't need to create collection. MongoDB creates collection


automatically, when you insert some document.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
118

>db. Nilesh.insert({"name" : "NileshKorade "})


>show collections

mycol
mycollection
system.indexes
Nilesh

The drop() Method:

MongoDB's db.collection.drop() is used to drop a collection from the database.

Syntax:

db.COLLECTION_NAME.drop()

Example:

>db.mycollection.drop()

The insert() Method:

To insert data into MongoDB collection, you need to use MongoDB's insert() or
save()method.

Syntax

>db.COLLECTION_NAME.insert(document)

Here mycol is our collection name, as created in previous tutorial. If the


collection doesn't exist in the database, then MongoDB will create this collection and
then insert document into it.In the inserted document if we don't specify the _id
parameter, then MongoDB assigns an unique ObjectId for this document.

_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes
are divided as follows:

_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes
incrementer)

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
119

To insert multiple documents in single query, you can pass an array of documents in
insert() command.

Example

>db.post.insert([

title: 'MongoDB Overview',

description: 'MongoDB is no sql database', by:


'NileshKorade',

url: 'http://www.NileshKorade.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100

},
])
OR in MongoDB
Syntax:

To query documents based on the OR condition, you need to use $or keyword.

>db.mycol.find(

{ $or: [

{key1: value1}, {key2:value2}

}).pretty()

Example

Below given example will show all the tutorials written by 'NileshKorade' or whose title
is 'MongoDB Overview'

>db.mycol.find({$or:[{"by":"NileshKorade"},{"title": "MongoDB Overview"}]}).pretty()

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
120

"_id": ObjectId(7df78ad8902c),

"title": "MongoDB Overview",

"description": "MongoDB is no sql database",


"by": "NileshKorade",

"url": "http://www.NileshKorade.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"

MongoDB Update() method

The update() method updates values in the existing document.

Syntax:

>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Example

Consider the mycol collectioin has following data.

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} {


"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{ "_id" : ObjectId(5983548781331adf45ec7), "title":"NileshKoradeOverview"}

Following example will set the new title 'New MongoDB Tutorial' of the
documents whose title is 'MongoDB Overview'

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
121

>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})

>db.mycol.find()

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"} {


"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{ "_id" : ObjectId(5983548781331adf45ec7), "title":"NileshKoradeOverview"}

By default mongodb will update only single document, to update multiple you need to
set a paramter 'multi' to true.
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'NewMongoDB
Tutorial'}},{multi:true})

The remove() Method:

MongoDB's remove() method is used to remove document from the collection.

remove() method accepts two parameters. One is deletion criteria and second is

justOne flag

1. deletion criteria : (Optional) deletion criteria according to documents will be


removed.

2. justOne : (Optional) if set to true or 1, then remove only one document.


Syntax:

>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Example

Consider the mycol collectioin has following data.

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} {


"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
122

{ "_id" : ObjectId(5983548781331adf45ec7), "title":"NileshKoradeOverview"}

Following example will remove all the documents whose title is 'MongoDB

Overview'

Remove only one

>db.mycol.remove({'title':'MongoDB Overview'})

>db.mycol.find()

{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{ "_id" : ObjectId(5983548781331adf45ec7), "title":"NileshKoradeOverview"}

If there are multiple records and you want to delete only first record, then set justOne
parameter in remove() method

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All documents

If you don't specify deletion criteria, then mongodb will delete whole documents
from the collection. This is equivalent of SQL's truncate command.

>db.mycol.remove()

>db.mycol.find()

The find() Method

MongoDB's find() method, explained in MongoDB Query Document accepts second


optional parameter that is list of fields that you want to retrieve. In MongoDB when you
execute find() method, then it displays all fields of a document. To limit this you need
to set list of fields with value 1 or 0. 1 is used to show the filed while 0 is used to hide
the field.

Syntax:

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
123

>db.COLLECTION_NAME.find({},{KEY:1})

Example

Consider the collection myycol has the following data

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} {


"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{ "_id" : ObjectId(5983548781331adf45ec7),

"title":"NileshKoradeOverview"}
Following example will display the title of the document while quering the
document.

>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
{"title":"NileshKoradeOverview"}

Please note _id field is always displayed while executing find() method, if you don't
want this field, then you need to set it as 0

The sort() Method

To sort documents in MongoDB, you need to use sort() method. sort() method accepts a
document containing list of fields along with their sorting order. To specify sorting
order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending
order.

Syntax:

>db.COLLECTION_NAME.find().sort({KEY:1})

Example

Consider the collection myycol has the following data

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
124

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} {


"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{ "_id" : ObjectId(5983548781331adf45ec7), "title":"NileshKoradeOverview"}

Following example will display the documents sorted by title in descending order.

>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"NileshKoradeOverview"}

{"title":"NoSQL Overview"}

{"title":"MongoDB Overview"}

Please note if you don't specify the sorting preference, then sort() method will display
documents in ascending order.

The Limit() Method

To limit the records in MongoDB, you need to use limit() method. limit() method
accepts one number type argument, which is number of documents that you want to
displayed.

Syntax:

>db.COLLECTION_NAME.find().limit(NUMBER)

Example

Consider the collection myycol has the following data

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} {


"_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}

{ "_id" : ObjectId(5983548781331adf45ec7), "title":"NileshKoradeOverview"}

Following example will display only 2 documents while quering the document.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
125

>db.mycol.find({},{"title":1,_id:0}).limit(2)
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}

If you don't specify number argument in limit() method then it will display all
documents from the collection.

15. MongoDB Skip() Method

Apart from limit() method there is one more method skip() which also accepts number
type argument and used to skip number of documents.

Syntax:

>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

Example:

Following example will only display only second document.

>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}

Please note default value in skip() method is 0

16. MongoDB Indexing

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

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


multiple fields.

>db.myc

Program:

> db.student20.update({'name':'sachin'},{$set:{'name':'shashir'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student20.find().pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
126

"roll_no" : 1,
"name" : "amit",
"addr" : "Loni"
}
{
"_id" : ObjectId("53c75c1cf4a21581aced6d2f"),
"roll_no" : 1,
"name" : "shashir",
"addr" : {
"At" : "Loni",
"Tal" : "Rahata",
"Dist" : "Ahemadnagar"
}
}
{
"_id" : ObjectId("53c75c51f4a21581aced6d30"),
"roll_no" : 101,
"name" : "sachin",
"percent_marks" : 60,
"addr" : "Pune"
}
{
"_id" : ObjectId("53c75c9bf4a21581aced6d31"),
"name" : "Rahul",
"Address" : "Kolhar"
}
{ "_id" : 1, "roll_no" : 1 }
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 4, "roll_no" : 4 }
{ "_id" : 5, "roll_no" : 5 }
{ "_id" : 6, "roll_no" : 6 }
{ "_id" : 7, "roll_no" : 7 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
{ "_id" : 35, "roll_no" : 15, "name" : "xyz", "addr" : "Abad" }
>
db.student20.update({'name':'sachin'},{$set:{'name':'shashir'}},{multi
:true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student20.find().pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),
"roll_no" : 1,
"name" : "amit",
"addr" : "Loni"
}
{
"_id" : ObjectId("53c75c1cf4a21581aced6d2f"),
"roll_no" : 1,
"name" : "shashir",

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
127

"addr" : {
"At" : "Loni",
"Tal" : "Rahata",
"Dist" : "Ahemadnagar"
}
}
{
"_id" : ObjectId("53c75c51f4a21581aced6d30"),
"roll_no" : 101,
"name" : "shashir",
"percent_marks" : 60,
"addr" : "Pune"
}
{
"_id" : ObjectId("53c75c9bf4a21581aced6d31"),
"name" : "Rahul",
"Address" : "Kolhar"
}
{ "_id" : 1, "roll_no" : 1 }
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 4, "roll_no" : 4 }
{ "_id" : 5, "roll_no" : 5 }
{ "_id" : 6, "roll_no" : 6 }
{ "_id" : 7, "roll_no" : 7 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
{ "_id" : 35, "roll_no" : 15, "name" : "xyz", "addr" : "Abad" }
> db.student20.find().limit(4)
{ "_id" : ObjectId("53c75bd3f4a21581aced6d2e"), "roll_no" : 1, "name"
: "amit", "addr" : "Loni" }
{ "_id" : ObjectId("53c75c1cf4a21581aced6d2f"), "roll_no" : 1, "name"
: "shashir", "addr" : { "At" : "Loni", "Tal" : "Rahata", "Dist" :
"Ahemadnagar" } }
{ "_id" : ObjectId("53c75c51f4a21581aced6d30"), "roll_no" : 101,
"name" : "shashir", "percent_marks" : 60, "addr" : "Pune" }
{ "_id" : ObjectId("53c75c9bf4a21581aced6d31"), "name" : "Rahul",
"Address" : "Kolhar" }
> db.student20.find().skip(2).pretty()
{
"_id" : ObjectId("53c75c51f4a21581aced6d30"),
"roll_no" : 101,
"name" : "shashir",
"percent_marks" : 60,
"addr" : "Pune"
}
{
"_id" : ObjectId("53c75c9bf4a21581aced6d31"),
"name" : "Rahul",
"Address" : "Kolhar"
}

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
128

{ "_id" : 1, "roll_no" : 1 }
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 4, "roll_no" : 4 }
{ "_id" : 5, "roll_no" : 5 }
{ "_id" : 6, "roll_no" : 6 }
{ "_id" : 7, "roll_no" : 7 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
{ "_id" : 35, "roll_no" : 15, "name" : "xyz", "addr" : "Abad" }
>
db.student20.find({$and:[{'roll_no':{$gt:5}},{'roll_no':{$lt:110}}]}).
pretty()
{> db.student20.find({},{'roll_no':1,'name':1}).pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),
"roll_no" : 1,
"name" : "amit"
}
{ "_id" : ObjectId("53c75c9bf4a21581aced6d31"), "name" : "Rahul" }
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 4, "roll_no" : 4 }
{ "_id" : 5, "roll_no" : 5 }
{ "_id" : 6, "roll_no" : 6 }
{ "_id" : 7, "roll_no" : 7 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
{ "_id" : 35, "roll_no" : 15, "name" : "xyz" }

"_id" : ObjectId("53c75c51f4a21581aced6d30"),
"roll_no" : 101,
"name" : "sachin",
"percent_marks" : 60,
"addr" : "Pune"
}
{ "_id" : 6, "roll_no" : 6 }
{ "_id" : 7, "roll_no" : 7 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
> db.student20.find({$or:[{'addr':'Loni'},{'addr':'Pune'}]}).pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),
"roll_no" : 1,
"name" : "amit",
"addr" : "Loni"
}
{
"_id" : ObjectId("53c75c51f4a21581aced6d30"),

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
129

"roll_no" : 101,
"name" : "sachin",
"percent_marks" : 60,
"addr" : "Pune"
}
> db.student20.find({'name':{$in:['sachin']}}).pretty()
{
"_id" : ObjectId("53c75c1cf4a21581aced6d2f"),
"roll_no" : 1,
"name" : "sachin",
"addr" : {
"At" : "Loni",
"Tal" : "Rahata",
"Dist" : "Ahemadnagar"
}
}
{
"_id" : ObjectId("53c75c51f4a21581aced6d30"),
"roll_no" : 101,
"name" : "sachin",
"percent_marks" : 60,
"addr" : "Pune"
}
> db.student20.find({'name':{$nin:['sachin']}}).pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),
"roll_no" : 1,
"name" : "amit",
"addr" : "Loni"
}
{
"_id" : ObjectId("53c75c9bf4a21581aced6d31"),
"name" : "Rahul",
"Address" : "Kolhar"
}
{ "_id" : 1, "roll_no" : 1 }
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 4, "roll_no" : 4 }
{ "_id" : 5, "roll_no" : 5 }
{ "_id" : 6, "roll_no" : 6 }
{ "_id" : 7, "roll_no" : 7 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
> db.student20.find({'name':'sachin'}).pretty()
{
"_id" : ObjectId("53c75c1cf4a21581aced6d2f"),
"roll_no" : 1,
"name" : "sachin",
"addr" : {
"At" : "Loni",

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
130

"Tal" : "Rahata",
"Dist" : "Ahemadnagar"
}
}
{
"_id" : ObjectId("53c75c51f4a21581aced6d30"),
"roll_no" : 101,
"name" : "sachin",
"percent_marks" : 60,
"addr" : "Pune"
}
> db.student20.find({'roll_no':{$lt:50}}).pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),
"roll_no" : 1,
"name" : "amit",
"addr" : "Loni"
}
{
"_id" : ObjectId("53c75c1cf4a21581aced6d2f"),
"roll_no" : 1,
"name" : "sachin",
"addr" : {
"At" : "Loni",
"Tal" : "Rahata",
"Dist" : "Ahemadnagar"
}
}
{ "_id" : 1, "roll_no" : 1 }
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 4, "roll_no" : 4 }
{ "_id" : 5, "roll_no" : 5 }
{ "_id" : 6, "roll_no" : 6 }
{ "_id" : 7, "roll_no" : 7 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
> db.student20.find({'roll_no':{$gt:50}}).pretty()
{
"_id" : ObjectId("53c75c51f4a21581aced6d30"),
"roll_no" : 101,
"name" : "sachin",
"percent_marks" : 60,
"addr" : "Pune"
}
> db.student20.find({'roll_no':{$ne:50}}).pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),
"roll_no" : 1,
"name" : "amit",
"addr" : "Loni"

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
131

}
{
"_id" : ObjectId("53c75c1cf4a21581aced6d2f"),
"roll_no" : 1,
"name" : "sachin",
"addr" : {
"At" : "Loni",
"Tal" : "Rahata",
"Dist" : "Ahemadnagar"
}
}
{
"_id" : ObjectId("53c75c51f4a21581aced6d30"),
"roll_no" : 101,
"name" : "sachin",
"percent_marks" : 60,
"addr" : "Pune"
}
{
"_id" : ObjectId("53c75c9bf4a21581aced6d31"),
"name" : "Rahul",
"Address" : "Kolhar"
}
{ "_id" : 1, "roll_no" : 1 }
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 4, "roll_no" : 4 }
{ "_id" : 5, "roll_no" : 5 }
{ "_id" : 6, "roll_no" : 6 }
{ "_id" : 7, "roll_no" : 7 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
> db.student20.remove({'roll_no':{$gt:8}},true)
WriteResult({ "nRemoved" : 1 })
> db.student20.find().pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),
"roll_no" : 1,
"name" : "amit",
"addr" : "Loni"
}
{
"_id" : ObjectId("53c75c9bf4a21581aced6d31"),
"name" : "Rahul",
"Address" : "Kolhar"
}
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 10, "roll_no" : 10 }
{ "_id" : 35, "roll_no" : 15, "name" : "xyz", "addr" : "Abad" }

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105
132

>
db.student20.remove({$and:[{'roll_no':{$gt:3}},{'roll_no':{$lt:8}}]})
WriteResult({ "nRemoved" : 3 })
> db.student20.find().pretty()
{
"_id" : ObjectId("53c75bd3f4a21581aced6d2e"),
"roll_no" : 1,
"name" : "amit",
"addr" : "Loni"
}
{
"_id" : ObjectId("53c75c9bf4a21581aced6d31"),
"name" : "Rahul",
"Address" : "Kolhar"
}
{ "_id" : 2, "roll_no" : 2 }
{ "_id" : 3, "roll_no" : 3 }
{ "_id" : 8, "roll_no" : 8 }
{ "_id" : 9, "roll_no" : 9 }
{ "_id" : 10, "roll_no" : 10 }
{ "_id" : 35, "roll_no" : 15, "name" : "xyz", "addr" : "Abad" }

/*
Assignment No. B5
Roll No.:
Full Name:
Title: Design and Implement any 5 query using MongoDB.

*/
<Your program here>

/* Output:
(As displayed after execution of above program.)
*/

Conclusion: Here we performed Indexing and querying with MongoDB using suitable example.

Department of Computer Engineering Dr D Y Patil School of Engineering


Lohegaon, Pune – 412 105

You might also like