Lab Manual DBMS (2)
Lab Manual DBMS (2)
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
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.
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
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.
2 Design and Develop MongoDB Queries using CRUD operations. (Use CRUD
operations, SAVE method, logical operators)
Normalization
Implementation :
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.
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
12 B4.Implement Map reduces operation with suitable example using MongoDB. 111
Assignment No. A1
Title: Study of Open Source Relational Databases: MySQL
Problem Statement / Aim: Upon Completion of this assignment students should able to learn
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:
RDBMS Terminology
Before we proceed to explain the MySQL database system, let us revise a few definitions related to the
database.
Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column: One column (data element) contains data of one and the same kind, for example the
column postcode.
Row: A row (= tuple, entry or record) is a group of related data. For example, the data of one
subscription.
Primary Key: A primary key is unique. A key value cannot occur twice in one table. With a key, you
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
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
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
MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL
[root@localhost]# mysql_secure_installation
4. Start Mysql
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,
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
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 –
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
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.
decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of
DATE – A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example,
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
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
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
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,
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.
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.
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
MySQL Transactions
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
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.
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.
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
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)
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.
For Example
// 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:
For example:
B) Modifying Table
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:
For example
4) Renaming Table
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.
The changes made in a table get automatically reflected in original table and vice versa.
A) Creating View
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;
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;
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
C)Dropping View
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.
A) Creating Index
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:
B) Displaying Index
C) Dropping Index
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.
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.
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)
2)Creating Table having specific field but all the records from existing table
B)Modifying Table
4)Renaming Table
mysql> Rename table Employee1 to Emptable;
Query OK, 0 rows affected (0.38 sec)
Creating Index
mysql> create table emp(empno int,name varchar(7),salary int);
Query OK, 0 rows affected (0.32 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)
/*
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.
*/
/* 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.
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
Theory:
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.
Problem Statement:
product_details(product_id,product_name,quantity,prices)
sales_details(sale_no,product_id,quantity,price,customer_name)
Theory:-
Syntax:
Syntax:
SELECT Query
SELECT query is used to retrieve the data from database.SELECT query never make any change
in database.
Syntax:
If we want to retrieve data from all the column of a table then instead of writing all the column
name use
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.
B) DISTINCT Clause
C) ORDERBY Clause
To arrange the displayed rows in ascending or descending order of a given column, ORDERBY Clause is
used.
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:
Delete
As per requirement , the records from existing table can be removed using delete command.Delete
command can have ‘Where clause optionally.
Syntax:
a) BETWEEN predicate
Between predicate is used to specify certain range of values. The AND keyword is used in this predicate.
Syntax:
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
Manager wants to view records of employee whose salary is not 8000 and 30000
c) LIKE Predicate
LIKE operator determines whether a specific character string matches the given pattern or not.
For Example
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
2)Max( )- This function return greatest value from specified column of the table.
Query to retrieve record of employee who gets maximum salary as compare to other employee
3)Count( )- This function return total number of values of specified column of the table
For example
4)Sum( )- This function returns the sum of all the values of specified column of the table.
For example
1)MID( )- This functions is used to extract substrings from column values of string type in a table
Syntax:
For example
2)LCASE( )- This functions is used to convert value of string column in Lowercase characters.
3)UCASE( )- This functions is used to convert value of string column in Uppercase characters.
4)ROUND( ) – This function is used to round a numeric field to number of nearest integer. It is used on
Decimal point values.
1)UNION- The union operator returns all distinct rows selected by either query;
Syntax:
2)UNION ALL- This returns all rows selected by either query including duplicates.
Syntax:
3)INTERSECT- This operator returns only those rows which are common to both the queries.
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.
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)
mysql>
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)
+-------------+
| MAX(salary) |
+-------------+
| 52000 |
+-------------+
1 row 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)
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
SQL> select product_id from product_details intersect select product_id from saes_details;
PRODUCT_ID
----------
5001
5002
5003
5004
5005
1 row deleted.
SQL> select *from product_details;
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.
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
Theory:
SQL Join
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
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:
(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
The INNER JOIN keyword selects records that have matching values in both tables.
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.
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.
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.
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)
mysql>
INNER JOIN
+------------+--------------+---------------+----------+-------+
6 rows in set (0.00 sec)
mysql>
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.
*/
/* 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.
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
2. Operation using PL/SQL block like Control structure and Exception Handling.
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 −
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;
/
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
% Attribute indicator
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
.. Range operator
Scalar
1
Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN.
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
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
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
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.
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
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 );
/
When the above code is executed, it produces the following result −
Customer Ramesh from Ahmedabad earns 2000
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
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
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
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
EXIT statement
1 The Exit statement completes the loop and control passes to the statement immediately
after the END LOOP.
2 CONTINUE statement
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!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!
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!
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;
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.
*/
/* 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.
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 −
%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
%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.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
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
If you check the records in customers table, you will find that the rows have been updated −
+----+----------+-----+-----------+----------+
| 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
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.
CURSOR c_customers IS
SELECT id, name, address FROM customers;
OPEN c_customers;
CLOSE c_customers;
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
Program:
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.)
*/
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.
Theory:
Stored Procedures
Procedures: Example
The below example creates a procedure ‘employer_details’ which gives the details of the employee.
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.
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;
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:
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.
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
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.
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.
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.
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
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.
[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.
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.
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.
For Example: Let's create a table 'product_check' which we can use to store messages when triggers are
fired.
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.
2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table 'product_check' before
each row is updated.
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.
4) AFTER UPDATE, Row Level: This trigger will insert a record into the table 'product_check' after
each row is updated.
Lets check the data in 'product_check' table to see the order in which the trigger is fired.
Output:
Mesage Current_Date
------------------------------------------------------------
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:
Table created.
Trigger created.
Trigger created.
no rows selected
Table created.
1 row created.
1 row created.
BOOK_STATUS_ID BOOKNAME
-------------- --------------------
11 DBMS
22 JAVA
Trigger dropped.
Trigger created.
1 row deleted.
STMT_TYPE
--------------------
UPDATE_TS
----------------------------------------------------------------------
AFTER DELETE
31-AUG-17 05.13.44.843418 PM
Trigger dropped.
Trigger created.
1 row deleted.
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
Trigger created.
Trigger created.
no rows selected
Table created.
1 row created.
1 row created.
BOOK_STATUS_ID BOOKNAME
-------------- --------------------
11 DBMS
22 JAVA
Trigger dropped.
Trigger created. 6 7 8 9 10 11 12 13
1 row deleted.
STMT_TYPE
--------------------
UPDATE_TS
---------------------------------------------------------------------------
AFTER DELET 14 E
31-AUG-17 05.13.44.843418 PM
Trigger dropped.
1 row deleted.
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
1 row created.
Trigger created.
1 row deleted.
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
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
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
Theory:
1. What is MongoDB?
Name: “Sagar”,
College: “MESCOE”,
Age: 26,
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 .
Mongo
/*
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
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.
Theory:
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
create a new database; if it doesn't exist otherwise it will return the existing database.
switched to db mydb
>db
mydb
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
In mongodb default database is test. If you didn't create any database then collections
Syntax: db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database.
>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 }
Syntax: db.COLLECTION_NAME.drop()
To insert data into MongoDB collection, you need to use MongoDB's insert() , update() or
save () method.
Syntax: db.COLLECTION_NAME.insert(document)
To query data from MongoDB collection, you need to use MongoDB's find() method.
Syntax: db.COLLECTION_NAME.find()
To display the results in a formatted way, you can use pretty() method.
Syntax: db.COLLECTION_NAME.find().pretty()
To display the results in a JSON format, you can use forEach() method.
Syntax: db.COLLECTION_NAME.find().forEach(printjson)
MongoDB's update() and save() methods are used to update document into a collection.
The update() method update values in the existing document while the save() method
replaces the existing document with the document passed in save() method.
Syntax:
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA,UPDATED_DATA)
The save() method replaces the existing document with the new document passed in save()
method.
Syntax: db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
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
Syntax: db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Name Description
$and Joins query clauses with a logical AND returns all documents that match the conditions of both
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:
"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"),
"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" }
{ "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" }
}
> 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"
}
]
> 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
Assignment No. B3
Problem Statement / Aim: Upon Completion of this assignment students should able to learn
Theory:
MongoDB Aggregation:
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
Descriptio
Expression n Example
db.mycol.aggregate([{$grou
Sums up the defined p : {_id :
documents in the
"$likes"}}}])
collection.
create duplicates.
document
s according to
previously applied
“$sort”-stage.
Example:
_id: ObjectId(7df78ad8902c)
title: 'MongoDB
Overview',
by_user: 'NileshKorade',
url:
'http://www.NileshKorade.com',
likes: 100
},
_id: ObjectId(7df78ad8902d)
by_user: 'NileshKorade',
url:
'http://www.NileshKorade.com',
likes: 10
},
_id: ObjectId(7df78ad8902e)
title: 'Neo4j
Overview',
by_user: 'Neo4j',
},
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:
"result" : [
"_id" : "NileshKorade",
"num_example" : 2
},
"_id" : "NileshKorade",
"num_example" : 1
],
"ok" : 1
MongoDB Indexing
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.
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.
ensureIndex() method also accepts list of options (which are optional), whose
list is given below:
dropDups Boolean removes all documents from the collection that contain
Example:
>db.mycol.ensureIndex({"title":1})
>db.mycol.ensureIndex({"title":1,"description":-1})
Program:
}
{
"_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 }
>
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'}}}])
>
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 }
>
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.
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:
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
MapReduce Command:
>db.collection.mapReduce(
{out: collection,
query: document,
Example:
Consider the following document structure storing user posts. The document
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
>db.posts.mapReduce(
function() { emit(this.user_id,1); },
{ query:{status:"active"}, out:"post_total"
})
Result:
{
"result" : "post_total",
"timeMillis" : 9, "counts"
:{
"input" : 4,
"emit" : 4,
"reduce" : 2,
"output" : 2
},
"ok" : 1,
(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); },
{query:{status:"active"}, out:"post_total"
}).find()
Result: The above query gives the following result which indicates that both users
Program:
"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.
Assignment No. B5
Problem Statement / Aim: Upon Completion of this assignment students should able to
learn Implement various queries using MongoDB
Theory:
MongoDB Commands: 1.
use Command:
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
>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.
Syntax:
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database
Syntax:
db.createCollection(name, options)
Options Document (Optional) Specify options about memory size and indexing
Examples:
db.createCollection("mycollection")
{ "ok" : 1 }
You can check the created collection by using the command show collections
>show collections
mycollection
mycol
mycollection
system.indexes
Nilesh
Syntax:
db.COLLECTION_NAME.drop()
Example:
>db.mycollection.drop()
To insert data into MongoDB collection, you need to use MongoDB's insert() or
save()method.
Syntax
>db.COLLECTION_NAME.insert(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)
To insert multiple documents in single query, you can pass an array of documents in
insert() command.
Example
>db.post.insert([
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: [
}).pretty()
Example
Below given example will show all the tutorials written by 'NileshKorade' or whose title
is 'MongoDB Overview'
"_id": ObjectId(7df78ad8902c),
"url": "http://www.NileshKorade.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
Syntax:
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
Example
Following example will set the new title 'New MongoDB Tutorial' of the
documents whose title is 'MongoDB Overview'
>db.mycol.find()
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})
remove() method accepts two parameters. One is deletion criteria and second is
justOne flag
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
Following example will remove all the documents whose title is 'MongoDB
Overview'
>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find()
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)
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()
Syntax:
>db.COLLECTION_NAME.find({},{KEY:1})
Example
{ "_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
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
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.
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
Following example will display only 2 documents while quering the document.
>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.
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:
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
>db.mycol.ensureIndex({"title":1})
>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"),
"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",
"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"
}
{ "_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"),
"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",
"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"
}
{
"_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" }
>
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.