DBMS Lab Manual Te
DBMS Lab Manual Te
INDEX
Sr. Page
No. Name of Assignment Date Remark
No.
Group A - SQL & PL/SQL
Study of Open Source Databases: MYSQL
1
Design and Develop SQL DDL statements which
2 demonstrate the use of SQL objects such as Table, View,
Index, Sequence, Synonym
Design at least 10 SQL queries for suitable database
application using SQL DML statements: Insert, Select,
3
Update, Delete with operators, functions and set
operator.
Design at least 10 SQL queries for suitable database
4 application using SQL DML statements: all types of Join,
Sub-Query and View.
Unnamed PL/SQL code block: Use of Control structure
5 and Exception handling is mandatory. Write a PL/SQL
block of code for the following requirements:-
Schema:
1. Borrower(Roll, Name, DateofIssue, NameofBook,
Status)
2. Fine (Roll, Date, Amt)
Accept Roll & 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.
Frame the problem statement for writing PL/SQL block
inline with above statement.
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
6 Cust_New with the data available in the table Cust_Old. 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 types
Page 1
Database Management System Laboratory
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
7
will be placed in distinction category if marks scored
arebetween 989 and900 category is first class, if marks
899 and825 category is Higher Second Class. Write a
PL/SQL block
for using procedure created with above requirement.
Group C Mini Project : Software Development Life cycle and other concepts
learnt in SoftwareEngineering Course throughout the implementation
Page 2
Database Management System Laboratory
Using the database concepts covered in Group A &
Group B, develop an application withfollowing details:
14 1. Follow the same problem statement decided in
Assignment -1 of Group A
2. Follow the Software Development Life cycle and
other concepts learnt in SoftwareEngineering
Course throughout the implementation.
3. Develop application considering:
Front End : Java/Perl/PHP/Python/Ruby/.net/any
other language
Backend : MongoDB/MySQL/Oracle
4. Test and validate application using Manual/Automation
testing
5. Student should develop application in group of 2-3
students and submit the Project Report which will
Page 3
Database Management System Laboratory
Assignment No. 1
Roll No.
Class T.E(E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 4
Database Management System Laboratory
Assignment No. 1
Title : Study of Open Source Databases:MySQL
Theory :
Page 5
Database Management System Laboratory
Referential Integrity: Referential Integrity makes sure that a foreign key value always
points to an existing row.
is a fast, easy-to-use RDBMS being used for many small and big businesses. is
developed, marketed, and supported by My SQLAB, which is a Swedish company. is
becoming so popular because of many good reasons:
• is released under an open-source license. So you have nothing to pay to use it.
• is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
• uses a standard form of the well-known SQL data language.
• works on many operating systems and with many languages including PHP, PERL,
C, C++, JAVA, etc.
• works very quickly and works well even with large datasets.
• is very friendly to PHP, the most appreciated language for web development.
• supports large databases, upto 50 million rows or more in a table.
The default file size limit for a table is 4GB, but you can increase this (if your operating
system can handle it) to a theoretical limit of 8 million tera bytes(TB).
• is customizable. The open-source GPL license allows programmers to modify the
software to fit their own specific environments.
Syntax
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer,
date, etc.).
The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
Page 6
Database Management System Laboratory
Example
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement.
The new table gets the same column definitions. All columns or specific columns can be
selected.
If you create a new table using an existing table, the new table will be filled with the existing
values from the old table.
Syntax
Each column in a database table is required to have a name and a data type.
SQL developers have to decide what types of data will be stored inside each and every table
column when creating a SQL table. The data type is a label and a guideline for SQL to
understand what type of data is expected inside of each column, and it also identifies how
SQL will interact with the stored data.
Page 7
Database Management System Laboratory
The first way specifies both the column names and the values to be inserted:
If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. However, make sure the order of the values is in the same
order as the columns in the table. The INSERT INTO syntax would be as follows:
SELECT Syntax
Here, column1, column2, ... are the field names of the table you want to select data from. If
you want to select all the fields available in the table, use the following syntax:
Page 8
Database Management System Laboratory
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND is
TRUE.
The OR operator displays a record if any of the conditions separated by OR is
TRUE.
AND Syntax
OR Syntax
NOT Syntax
AND Example : The following SQL statement selects all fields from "Customers" where
country is "Germany" AND city is "Berlin":
Example
OR Example : The following SQL statement selects all fields from "Customers" where city
is "Berlin" OR "München":
Example
NOT Example : The following SQL statement selects all fields from "Customers" where
country is NOT "Germany":
Example
Page 9
Database Management System Laboratory
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" column:
Example
The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a
table, a column often contains many duplicate values; and sometimes you only want to list
the different (distinct) values. The SELECT DISTINCT statement is used to return only
distinct (different) values.
The following SQL statement selects only the DISTINCT values from the "Country" column
in the "Customers" table:
Example
The WHERE clause is used to extract only those records that fulfill a specified condition.
WHERE Syntax
Page 10
Database Management System Laboratory
The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:
Example
SQL requires single quotes around text values (most database systems will also allow double
quotes).
Example
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
DELETE Syntax
Note: Be careful when deleting records in a table! Notice the WHERE clause in the
DELETE statement. The WHERE clause specifies which record(s) that should be deleted. If
you omit the WHERE clause, all records in the table will be deleted!
The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
Page 11
Database Management System Laboratory
Example
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
The COUNT() function returns the number of rows that matches a specified criteria.
Page 12
Database Management System Laboratory
COUNT() Syntax
AVG() Syntax
SUM() Syntax
COUNT() Example
Example
AVG() Example
The following SQL statement finds the average price of all products:
Example
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails"
table:
Example
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
The percent ( % ) sign and the underscore ( _ )can also be used in combinations!
Page 13
Database Management System Laboratory
LIKE Syntax
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
The following SQL statement selects all customers with a CustomerName starting with "a":
Example
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
The following SQL statement selects all customers with a CustomerName that have "or" in
any position:
Example
The following SQL statement selects all customers with a CustomerName that have "r" in
the second position:
Example
Page 14
Database Management System Laboratory
The following SQL statement selects all customers with a Customer Name that starts with
"a" and are at least 3 characters in length:
Example
The following SQL statement selects all customers with a Customer Name that starts with
"a" and ends with "o":
Example
The following SQL statement selects all customers with a CustomerName that NOT starts
with "a":
Example
FAQ ?
Page 15
Database Management System Laboratory
Assignment No. 2
Design and Develop SQL DDL statements which demonstrate
Title the use of SQL objects such as Table, View, Index, Sequence,
Synonym
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 16
Database Management System Laboratory
Assignment No. 2
Title: Design and Develop SQL DDL statements which demonstrate the use of SQL objects
such as Table, View , Index, Sequence, Synonym
• If you want only structure without records then select statement must have
condition. Syntax:
Page 17
Database Management System Laboratory
Constraints
The definition of a table may include the specification of integrity constraints. Basically
two types of constraints are provided: column constraints are associated with a single
column whereas table constraints are typically associated with more than one column. A
constraint can be named. It is advisable to name a constraint in order to get more
meaningful information when this constraint is violated due to, e.g., an insertion of a
tuple that violates the constraint. If no name is specified for the constraint, Oracle
automatically generates a name of the pattern SYS C<number>.Rules are enforced on
data being stored in a table, are called Constraints.
Both the Create table & Alter Table SQL can be used to write SQL sentences that
attach constraints.
Basically constraints are of three types
1) Domain
- Not Null
- Check
2) Entity
- Primary Key
- Unique
3) Referential
- Foreign key
Page 18
Database Management System Laboratory
CREATE TABLE
<tableName>
(<ColumnName>
datatype(size),
<ColumnName> datatype(size),….,
CHECK (columnName condition));
After table creation
Alter table tablename
Add constraints constraintname ckeck(condition)
The PRIMARY KEY Constraint
A primary key is one or more column(s) in a table used to uniquely identify each row in
the table.
• A table can have only one primary key.
• Can not be left blank
Page 19
Database Management System Laboratory
Page 20
Database Management System Laboratory
A foreign key is a column( or group of columns) whose values are derived from primary
key or unique key of some other table.
Page 21
Database Management System Laboratory
Page 22
Database Management System Laboratory
Case2:-
Alter table <table_name>
Modify(colume_name 1 datatype size(),
colume_name 2 datatype size(),
…...
colume_name n datatype size());
After you create a table, you may need to change the table structures because you need to have
a column definition needs to be changed. Alter table statement can be used for this purpose.
You can add columns to a table using the alter table statement with the ADD clause.
E.g. Suppose you want to add enroll_no in the student table then we write
Alter table student Add(enroll_no number(10));
You can modify existing column in a table by using the alter table statement with modify
clause.
E.g. Suppose you want to modify or chang the size of previously defined field name in the
student table then we write
Drop table command remnoves the definitions of an oracle table.When you drop a table
,the database loses all the data in the table and all the indexes associated with it.
e.g drop table student;
Truncate table command
Syntax:-
Trunc table<table_name>
The truncate table statement is used to remove all rows from a table and to release the storage
space used by the table.
e.g.Trunc table student;
Page 23
Database Management System Laboratory
Rename<oldtable_name> to<newtable_name>
Automatically :- A unique index is created automatically when you define a primary key or
unique key constraint in a table definition.
Manually :- users can create non unique indexes or columns to speed up access time to the rows.
Syntax:
Create index<index_name> On table(column[ , column]…);
Eg. Create index emp_ename_idx On emp(ename);
When to create an index
a) The column is used frequently in the WHERE clause or in a join condition.
b) The column contains a wide range of values.
c) The column contains a large number of values.
To display created index of a table
eg.
Removing an Index
Syntax:-
Drop index <index_name>;
Page 24
Database Management System Laboratory
The optional clause or replace re-creates the view if it already exists. <column(s)> names the
columns of the view. If <column(s)> is not specified in the view definition, the columns of the
view get the same names as the attributes listed in the select statement (if possible).
Example: The following view contains the name, job title and the annual salary of employees
working in the department 20:
Create view DEPT20 as
select ENAME, JOB, SAL 12 ANNUAL SALARY from EMP where DEPTNO = 20;
In the select statement the column alias ANNUAL SALARY is specified for the expression
SAL∗12 and this alias is taken by the view. An alternative formulation of the above view
definition is
Create view DEPT20 (ENAME, JOB, ANNUAL SALARY) as select ENAME, JOB, SAL
12 from EMP where DEPTNO = 20;
A view can be used in the same way as a table, that is, rows can be retrieved from a view(also
respective rows are not physically stored, but derived on basis of the select statement inthe view
definition), or rows can even be modified. A view is evaluated again each time it is accessed. In
Oracle SQL no insert, update, or delete modifications on views are allowed
that use one of the following constructs in the view definition:
• Joins
• Aggregate function such as sum, min, max etc.
• set-valued subqueries (in, any, all) or test for existence (exists)
• group by clause or distinct clause
In combination with the clause with check option any update or insertion of a row into the view
is rejected if the new/modified row does not meet the view definition, i.e., these rows would not
be selected based on the select statement. A with check option can be named using the constraint
clause.
Page 25
Database Management System Laboratory
Sequence:
A sequence is a database object, which can generate unique, sequential integer values. It can be
used to automatically generate primary key or unique key values. A sequence can be either in an
ascending or descending order.
Syntax :
Create
sequence<sequence_name>
[increment by n]
[start with n]
[{maxvalue n |
nomaxvalue}] [{minvalue n|
nominvalue}] [{cycle |
nocycle}]
[{cache n| nocache}];
Increment by n Specifies the interval betweensequence number where n
is an integer. If this clause is omitted, the
sequence is increment by 1.
Start with n Specifies the first sequence number to be generated. If this clause
is omitted ,the sequence is start with 1.
Maxvalue n Specifies the maximum value, the sequence can generate
Nomax value n Specifies the maximum value of 10e27-1 for an ascending
sequence & -1 for descending sequence. This is a default option.
Cycle Specifies that the sequence continues to generate values from the
beginning
Page 26
Database Management System Laboratory
After creating a sequence we can access its values with the help of pseudo columns
like curval & nextval.
Nextval : nextval returns initial value of the sequence when reference to for the first
time. Last references to the nextval will increment the sequence using the increment
by clause & returns the new value.
Curval : curval returns the current value of the sequence which is the value returned
by the last reference to last value.
Modifyning a sequence:
The sequence can be modified when we want to perform the following :
□
Set or eliminate minvalue or maxvalue
□
Change the increment value.
[start with n]
[{maxvalue n | nomaxvalue}]
[{minvalue n| nominvalue}]
[{cycle | nocycle}]
[{cache n| nocache}];
Synonym:
A synonym is a database object,which is used as an alias(alternative name)for a
table,view or sequence.
Syntax:-
Create[public]synonym
<synonym_name>for<table_name>;
In the syntax
Page 27
Database Management System Laboratory
Page 28
Database Management System Laboratory
maximum
precision
fixed-point
of 126
numbers:
binary
DEC
digits,
DECIMAL
which is
NUMERIC
roughly
equivalent
floating-
to 38
The point:
decimal
The precisio DOUBLE
digits
precision n p can PRECISIO
The precision The scale
p can range N FLOAT
p can range s can
range from 1 binary_dou
from 1 to 38. range
Number having from 1 to to 38. ble
from -84
NUMBER(p,s) precision p and 38. binary_floa
The scale s to 127.
scale s. The scales The scale t
can range For
can range s can
from -84 to floating
from -84 range integers:
127. point
to 127. from -84 INTEGER
don't
to 127. INT
specify
SMALLIN
p,s
T
REAL
simple_inte
has a
ger(10g)
maximum
precision
BOOLEA
of 63
N
binary
REAL
digits,
which is
roughly
equivalent
to 18
decimal
digits
signed integers magnitud
PLS_INTEGE PLS_INTEGER PL/SQL PL/SQL e range is
PL/SQL only
R values require Only only -
less storage and 21474836
Page 29
Database Management System Laboratory
provide better 47 ..
performance 21474836
than NUMBER 47
values.
So use
PLS_INTEGER
where you can!
NATURA
magnitud L
signed integers e range is NATURA
(older slower - LN
BINARY_INT
version of 21474836 POSITIVE
EGER
PLS_INTEGER 47 .. POSITIVE
) 21474836 N
47 SIGNTYP
E
32760
bytes Note
Character data this is
of variable smalller
2 2 Gigabytes -
length (A bigger 2 than the
LONG Gigabyt but now
version the Gigabytes maximum
es deprecated
VARCHAR2 width of a
datatype) LONG
column
from
from January 1,
from
January 4712 BC
January 1,
1, 4712 from January to
4712 BC
BC to 1, 4712 BC to December
DATE Valid date range to
Decemb December 31, 31, 9999
December
er 31, 9999 AD. AD.
31, 4712
9999 (in
AD.
AD. Oracle7 =
4712 AD)
Accepted
the number of
TIMESTAMP values of
digits in the
(fractional_sec fractional_sec
fractional part of - -
onds_precision onds_precisio
the SECOND
) n are 0 to 9.
datetime field. (default = 6)
TIMESTAMP Accepted
(fractional_sec As above with values of
onds_precision time zone fractional_sec
- -
) WITH displacement onds_precisio
{LOCAL} value n are 0 to 9.
TIMEZONE (default = 6)
INTERVAL Time in years - - Accepted
Page 30
Database Management System Laboratory
Hexadeci
Hexadecimal
mal string
string
representi
representing the
ng the
unique address
unique
of a row in its
ROWID 8 bytes 10 bytes 10 bytes address of
table. (primarily
a row in
for values
its table.
returned by the
(primarily
ROWID
for values
pseudocolumn.) returned
Page 31
Database Management System Laboratory
by the
ROWID
pseudocol
umn.)
universal
rowid -
UROWID
Hex string
representi
ng the
logical
The See
Hex string address of
maximu CHARTO
representing the The maximum a row of
m size ROWID
logical address size and default an index-
N/A and and the
of a row of an is 4000 bytes organized
default is package:
index-organized table,
4000 DBMS_R
table either
bytes OWID
physical,
logical, or
foreign
(non-
Oracle)
Binary format of
an operating
system
MLSLABEL label.This
datatype is used
with Trusted
Oracle7.
Character Large 4Gigabyte 4Gigaby 4Gigabyt
CLOB Object S tes 4Gigabytes es
National
Character Large 4Gigaby 4Gigabyt
NCLOB 4Gigabytes
tes es
Object
Binary Large 4Gigaby 4Gigabyt
BLOB 4Gigabytes
Object tes es
The size
of a
BFILE is
system
dependent
pointer to binary 4Gigaby but cannot
BFILE 4Gigabytes
file on disk tes exceed
four
gigabytes
(2**32 -
1 bytes).
Page 32
Database Management System Laboratory
Populate
with
XML
from a
CLOB or
VARCH
XMLType XML data - - 4Gigabytes AR2.
or query
from
another
XMLTyp
e column.
Page 33
Database Management System Laboratory
Assignment No. 3
Roll No.
Date
Signature
Page 34
Database Management System Laboratory
Assignment No. 3
Title:- Design at least 10 SQL queries for suitable database application using SQL DML
statements: Insert, Select, Update, Delete with operators, functions, and set operator.
To insert string data types, it is required to keep all the values into double or single quote, for
example:-"value".
Inserting Data from Command Prompt:
This will use SQL INSERT INTO command to insert data into table tutorials_tbl.
Example:
Following example will create 3 records into tutorials_tbl table:
Page 35
Database Management System Laboratory
□ You can use one or more tables separated by comma to include various conditions using
a WHERE clause, but WHERE clause is an optional part of SELECT command.
□ You can fetch one or more fields in a single SELECT command.
□ You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
□ You can specify any condition using WHERE clause.
□ You can specify an offset using OFFSET from where SELECT will start returning
records. By default offset is zero.
□ You can limit the number of returns using LIMIT attribute.
The SQL SELECT statement returns a result set of records from one or more tables.
A SELECT statement retrieves zero or more rows from one or more database tables or
database views. In most applications, SELECT is the most commonly used Data Manipulation
Language (DML) command. As SQL is a declarative programming language, SELECT queries
specify a result set, but do not specify how to calculate it. The database translates the query into a
"query plan" which may vary between executions, database versions and database software. This
functionality is called the "query optimizer" as it is responsible for finding the best possible
execution plan for the query, within applicable constraints.
The SELECT statement has many optional clauses:
□ WHERE specifies which rows to retrieve.
Page 36
Database Management System Laboratory
□ GROUP BY groups rows sharing a property so that an aggregate function can be applied
to each group.
□ HAVING selects among the groups defined by the GROUP BY clause.
□ ORDER BY specifies an order in which to return the rows.
□ AS provides an alias which can be used to temporarily rename tables or columns.
WHERE Clause
We have seen SQL SELECT command to fetch data from table. We can use a conditional
clause called WHERE clause to filter out results. Using WHERE clause, we can specify a
selection criteria to select required records from a table.
Syntax:
Here is generic SQL syntax of SELECT command with WHERE clause to fetch data from
table:
□ You can use one or more tables separated by comma to include various conditions using
a WHERE clause, but WHERE clause is an optional part of SELECT command.
□ You can specify any condition using WHERE clause.
□ You can specify more than one conditions using AND or OR operators.
□ A WHERE clause can be used along with DELETE or UPDATE SQL command also to
specify a condition.
The WHERE clause works like an if condition in any programming language. This clause is
used to compare given value with the field value available in table. If given value from outside
is equal to the available field value in table, then it returns that row.
Here is the list of operators, which can be used with WHERE clause.
Assume field A holds 10 and field B holds 20, then:
= Checks if the values of two operands are equal or not, if yes then (A = B) is not true.
condition becomes true.
!= Checks if the values of two operands are equal or not, if values are (A != B) is true.
not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of right (A > B) is not true.
operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the (A >= B) is not
value of right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value (A <= B) is true.
of right operand, if yes then condition becomes true.
Page 37
Database Management System Laboratory
The WHERE clause is very useful when you want to fetch selected rows from a table, especially
when you use Join.
It is a common practice to search records using Primary Key to make search fast.
If given condition does not match any record in the table, then query would not return any row.
Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You can
make your search case sensitive using BINARY keyword as follows:
Page 38
Database Management System Laboratory
GROUP BY Clause
You can use GROUP BY to group values from a column, and, if you wish, perform calculations
on that column. You can use COUNT, SUM, AVG, etc., functions on the grouped column.
To understand GROUP BY clause, consider an employee_tbl table, which is having the
following records:
Now, suppose based on the above table we want to count number of days each employee did
work.
If we will write a SQL query as follows, then we will get the following result:
But this is not serving our purpose, we want to display total number of pages typed by each
person separately. This is done by using aggregate functions in conjunction with a GROUP
BY clause as follows:
Page 39
Database Management System Laboratory
+ + +
| name | COUNT(*) |
+ + +
| Jack | 2|
| Jill | 1|
| John | 1|
| Ram | 1|
| Zara | 2|
+ + +
5 rows in set (0.04 sec)
We will see more functionality related to GROUP BY in other functions like SUM, AVG, etc.
COUNT Function
COUNT Function is the simplest function and very useful in counting the number of records,
which are expected to be returned by a SELECT statement.
To understand COUNT function, consider an employee_tbl table, which is having the following
records:
> SELECT * FROM employee_tbl;
+ + + + +
| id | name | work_date | daily_typing_pages |
+ + + + +
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+ + + + +
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to count total number of rows in this table, then
you can do it as follows:
Similarly, if you want to count the number of records for Zara, then it can be done as follows:
Page 40
Database Management System Laboratory
| COUNT(*) |
+ +
| 2|
+ +
1 row in set (0.04 sec)
NOTE: All the SQL queries are case insensitive so it does not make any difference if you give
ZARA or Zara in WHERE condition.
MAX Function
MAX function is used to find out the record with maximum value among a record set.
To understand MAX function, consider an employee_tbl table, which is having the following
records:
Now, suppose based on the above table you want to fetch maximum value of
daily_typing_pages, then you can do so simply using the following command:
You can find all the records with maximum value for each name using GROUP BY clause as
follows:
Page 41
Database Management System Laboratory
| 1 | John | 250 |
| 2 | Ram | 220 |
| 5 | Zara | 350 |
+ + + +
5 rows in set (0.00 sec)
You can use MIN Function along with MAX function to find out minimum value as well. Try
out the following example:
MIN Function
MIN function is used to find out the record with minimum value among a record set.
To understand MIN function, consider an employee_tbl table, which is having the following
records:
Now, suppose based on the above table you want to fetch minimum value of daily_typing_pages,
then you can do so simply using the following command:
Page 42
Database Management System Laboratory
You can find all the records with minimum value for each name using GROUP BY clause as
follows:
You can use MIN Function along with MAX function to find out minimum value as well. Try
out the following example:
AVG Function
AVG function is used to find out the average of a field in various records.
To understand AVG function, consider an employee_tbl table, which is having following
records:
Now, suppose based on the above table you want to calculate average of all the
dialy_typing_pages, then you can do so by using the following command:
Page 43
Database Management System Laboratory
You can take average of various records set using GROUP BY clause. Following example will
take average all the records related to a single person and you will have average typed pages by
every person.
SUM Function
SUM function is used to find out the sum of a field in various records.
To understand SUM function, consider an employee_tbl table, which is having the following
records:
Now, suppose based on the above table you want to calculate total of all the dialy_typing_pages,
then you can do so by using the following command:
Page 44
Database Management System Laboratory
+ +
| 1610 |
+ +
1 row in set (0.00 sec)
You can take sum of various records set using GROUP BY clause. Following example will sum
up all the records related to a single person and you will have total typed pages by every person.
HAVING clause
The HAVING clause is used in the SELECT statement to specify filter conditions for group of
rows or aggregates. The HAVING clause is often used with the GROUP BY clause. When
using with the GROUP BY clause, you can apply a filter condition to the columns that appear in
the GROUP BY clause. If the GROUP BY clause is omitted, the HAVING clause behaves like
the WHERE clause. Notice that the HAVING clause applies the condition to each group of
rows, while the WHERE clause applies the condition to each individual row.
Examples of using HAVING clause
Let‟s take a look at an example of using HAVING clause.
We will use the orderdetails table in the sample database for the sake of demonstration.
We can use the GROUP BY clause to get order number, the number of items sold per order and
total sales for each:
SELECT ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
Page 45
Database Management System Laboratory
Now, we can find which order has total sales greater than $1000. We use the HAVING clause
on the aggregate as follows:
SELECT ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING total > 1000
We can construct a complex condition in the HAVING clause using logical operators such
as OR and AND. Suppose we want to find which order has total sales greater than $1000 and
contains more than 600 items, we can use the following query:
SELECT ordernumber,
sum(quantityOrdered) AS itemsCount,
sum(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING total > 1000 AND itemsCount > 600
The HAVING clause is only useful when we use it with the GROUP BY clause to generate the
output of the high-level reports. For example, we can use the HAVING clause to answer some
kinds of queries like give me all the orders in this month, this quarter and this year that have total
sales greater than 10K.
Page 46
Database Management System Laboratory
UPDATE Query
There may be a requirement where existing data in a table needs to be modified. You can do so
by using SQL UPDATE command. This will modify any field value of any table.
Syntax:
Here is generic SQL syntax of UPDATE command to modify data into table:
UPDATE table_name SET field1=new-value1, field2=new-value2
[WHERE Clause]
□ You can update one or more field altogether.
□ You can specify any condition using WHERE clause.
□ You can update values in a single table at a time.
The WHERE clause is very useful when you want to update selected rows in a table.
Updating Data from Command Prompt:
This will use SQL UPDATE command with WHERE clause to update selected data into table
tutorials_tbl.
Example:
Following example will update tutorial_title field for a record having tutorial_id as 3.
UPDATE tutorials_tbl
SET tutorial_title='Learning JAVA'
WHERE tutorial_id=3;
DELETE Query
If you want to delete a record from any table, then you can use SQL command DELETE
FROM. You can use this command at > prompt as well as in any script like PHP.
Syntax:
Here is generic SQL syntax of DELETE command to delete data from a table:
□ If WHERE clause is not specified, then all the records will be deleted from the given
table.
□ You can specify any condition using WHERE clause.
□ You can delete records in a single table at a time.
The WHERE clause is very useful when you want to delete selected rows in a table.
Deleting Data from Command Prompt:
This will use SQL DELETE command with WHERE clause to delete selected data into table
tutorials_tbl.
Example:
Following example will delete a record into tutorial_tbl whose tutorial_id is 3.
Page 47
Database Management System Laboratory
3. List out the employees who are earning salary between 3000 and 4500
Select * from employee where salary between 3000 and 4500
7. List out the employees whose name start with “S” and end with “H”
Select * from employee where last_name Like 'S%H';
8. List out the employees whose name length is 5 and start with “S”
Select * from employee where last_name like 'S _';
9. List out the employees who are working in department 10 and draw the salaries more
than 3500
Select * from employee where department_id=10 and salary>3500
10. List out the employees who are not receiving commission.
Select * from employee where commission is Null
11. List out the employee id, last name in ascending order based on the employee id.
Select employee_id, last_name from employee order by employee_id
12. List out the employee id, name in descending order based on salary column
Select employee_id, last_name, salary from employee order by salary desc
Page 48
Database Management System Laboratory
13. List out the employee details according to their last_name in ascending order and
salaries in descending order
Conclusion: Thus we have studied to use & implement various DML queries.
FAQ :
1. Explain DML.
Page 49
Database Management System Laboratory
Assignment No. 4
Design at least 10 SQL queries for suitable database
Title application using SQL DML statements: all types of Join,
Sub-Query and View.
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 50
Database Management System Laboratory
Assignment No: 4
Title:- Design at least 10 SQL queries for suitable database application using SQL DML
statements: all types of Join, Sub-Query and View.
Objectives:- To study all types of Join, Sub-Query and View SQL statements.
- Statements generally compares two columns from two columns with the equivalence
operator =.
- This type of join can be used in situations where selecting only those rows that have
values in common in the columns specified in the ON clause, is required.
• Syntax :
(ANSI style)
• List the employee details along with branch names to which they belong.
Page 51
Database Management System Laboratory
Emp(empno,fname,lname,dept,desig,branchno)
Branch(bname,branchno)
Select e.empno, e.fname, e.lname, e.dept, b.bname, e.desig from emp e, branch b on where
b.branchno=e.branchno;
Eg. List the customers along with the account details associated with them.
Customer(custno,fname,lname)
Acc_cust_dtls(fdno,custno)
Acc_mstr(accno,branchno,curbal)
Branch_mstr(name,branchno)
Page 52
Database Management System Laboratory
All the employee details have to be listed even though their corresponding contact information is not
present. This indicates all the rows from the first table will be displayed even though there exists no
matching rows in the second table.
• Select e.empno, e.fname, e.lname, e.dept, c.cntc_type, c.cntc_data from emp_mstr e right join
cntc_dtls c on e.empno=c.codeno;
• Select e.empno, e.fname, e.lname, e.dept, c.cntc_type, c.cntc_data from emp_mstr e cntc_dtls c
where e.empno(+)=c.codeno;
Since the RIGHT JOIN returns all the rows from the second table even if there are no matches in the
first table.
Cross join
A cross join returns what known as a Cartesian Product. This means that the join combines
every row from the left table with every row in the right table. As can be imagined, sometimes
this join produces a mess, but under the right circumstances, it can be very useful. This type of
join can be used in situation where it is desired, to select all possible combinations of rows &
columns from both tables. The kind of join is usually not preferred as it may run for a very long
time & produce a huge result set that may not be useful.
• Create a report using cross join that will display the maturity amounts for predefined deposits,
based on min & max period fixed/ time deposit.
• Tables
Tem_fd_amt(fd_amt)
Fd_mstr(minprd,maxprd,intrate)
Self join
Page 53
Database Management System Laboratory
Example
- Emp_mgr(empno,fname, lname,mgrno)
• Select e.empno,e.fname,e.lname, m.fname “manager” from emp_mgr e, emp_mgr m where
e.mgrno=m.empno;
Three tire Architecture:
A three-tier architecture is a client-server architecture in which the functional process logic, data
access, computer data storage and user interface are developed and maintained as independent modules
on separate platforms. Three-tier architecture is a software design pattern and a well-established
software architecture.
In a Three-tier architecture, the client machine acts as merely a front end and does not contain
any direct database calls. Instead, the client end communicates with an application server, usually
through a forms interface. The application server in turn communicates with a
database system to access data. The business logic of the application, which says what actions to carry
out under what conditions, is embedded in the application server, instead of being distributed across
multiple clients. Three-tier applications are more appropriate for large applications, and for applications
that run on the World Wide Web.
Page 54
Database Management System Laboratory
1. Presentation Tier: Occupies the top level and displays information related to services available
on a website. This tier communicates with other tiers by sending results to the browser and other
tiers in the network.
2. Application Tier: Also called the middle tier, logic tier, business logic or logic tier, this tier is
pulled from the presentation tier. It controls application functionality by performing detailed
processing.
3. Data Tier: Houses database servers where information is stored and retrieved. Data in this tier is
kept independent of application servers or business logic.
Conclusion: Thus we have studied to use & implement various join operation with nested queries.
FAQ:
1. Explain Join Function.
2. Enlist the different types of join operations.
3. Explain CROSS Join explain with example.
4. Explain Natural join explain with example.
5. Explain Inner join explain with example.
6. Explain Outer join explain with example.
7. What is the use of nested Query. Explain with Example.
Page 55
Database Management System Laboratory
Assignment No. 5
Unnamed PL/SQL code block: Use of Control structure and
Title Exception handling is mandatory.
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 56
Database Management System Laboratory
Assignment No: 5
Title:- Unnamed PL/SQL code block: Use of Control structure and Exception handling is mandatory.
Frame the problem statement for writing PL/SQL block inline with above statement.
The development of database applications typically requires language constructs similar to those that
can be found in programming languages such as C, C++, or Pascal. These constructs are necessary in
order to implement complex data structures and algorithms. A major restriction of the database
language SQL, however, is that many tasks cannot be accomplished by using only the provided
language elements.
PL/SQL allows users and designers to develop complex database applications that require the usage of
control structures and procedural elements such as procedures, functions, and modules.
The basic construct in PL/SQL is a block. Blocks allow designers to combine logically related (SQL-)
statements into units. In a block, constants and variables can be declared, and variables can be used to
store query results. Statements in a PL/SQL block include SQL statements, control structures (loops),
condition statements (if-then-else), exception handling, and calls of other PL/SQL blocks.
PL/SQL blocks that specify procedures and functions can be grouped into packages. A package is
similar to a module and has an interface and an implementation part. Oracle o ffers several predefined
packages, for example, input/output routines, file handling, job scheduling etc. (see directory
$ORACLE HOME/rdbms/admin).
Another important feature of PL/SQL is that it o ffers a mechanism to process query results in a tuple-
oriented way, that is, one tuple at a time. For this, cursors are used. A cursor basically is a pointer to a
query result and is used to read attribute values of selected tuples into variables. A cursor typically is
Page 57
Database Management System Laboratory
used in combination with a loop construct such that each tuple read by the cursor can be processed
individually.
Advantages of PL/SQL:-
Following are some advantages of Pl/SQL
1) Support for SQL :-PL/SQL is the procedural language extension to SQL supports all the
functionalities of SQL.
2) Improved performance:- In SQL every statement individually goes to the ORACLE server, get
processed and then execute. But in PL/SQL an entire block of statements can be sent to ORACLE
server at one time, where SQL statements are processed one at atime.PL/SQL block statements
drastically reduce communication between the application and ORACLE. This helps in improving the
performance.
3) Higher Productivity:- Users use procedural features to build applications.PL/SQL code is written in
the form of PL/SQL block.PL/SQL blocks can also used in other ORACLE Forms, ORACLE reports.
This code reusability increases the programmers productivity.
4) Portability :- Applications written in PL/SQL are portable. We can port them from one environment
to any computer hardware and operating system environment running ORACLE.
5) Integration with ORACLE :-Both PL/SQL and ORACLE are SQL based.PL/SQL variables have
datatypes native to the oracle RDBMS dictionary. This gives tight integration with ORACLE.
Features of PL/SQL:-
1) We can define and use variables and constants in PL/SQL.
2) PL/SQL provides control structures to control the flow of a program. The control structures
supported by PL/SQL are if..Then, loop, for..loop and others.
3) We can do row by row processing of data in PL/SQL.PL/SQL supports row by row processing using
the mechanism called cursor.
4) We can handle pre-defined and user-defined error situations. Errors are warnings and called as
exceptions in PL/SQL.
The basic unit of code in any PL/SQL program is a block. All PL/SQL programs are composed of
blocks. These blocks can be written sequentially.
Page 58
Database Management System Laboratory
DECLARE
Declaration section
BEGIN
Executable section
EXCEPTION
Exception handling section
END;
Where
1) Declaration section
PL/SQL variables, types, cursors, and local subprograms are defined here.
2) Executable section
Procedural and SQL statements are written here. This is the main section of the block.
This section is required.
3) Exception handling section
Error handling code is written here
This section is optional whether it is defined within body or outside body of program.
Conditional statements check the validity of a condition and accordingly execute a set of statements.
The conditional statements supported by Pl/SQL is
1) IF..THEN
2) IF..THEN..ELSE
3) IF..THEN..ELSIF
1) IF..THEN
Syntax1:-
If condition THEN
Statement list
END IF;
2) IF..THEN..ELSE
Syntax 2:-
IF condition THEN
Statement list
ELSE
Statements
END IF;
3) IF..THEN..ELSIF
Syntax 3:-
If condition THEN
Statement list
ELSIF condition THEN
Statement list
ELSE
Statement list
END IF;
END IF;
Page 59
Database Management System Laboratory
2) CASE Expression :CASE expression can also be used to control the branching logic within
PL/SQL blocks. The general syntax is
CASE
WHEN <expression> THEN <statements>;
WHEN <expression> THEN <statements>;
.
.
ELSE
<statements>;
END CASE;
Here expression in WHEN clause is evaluated sequentially. When result of expression is TRUE, then
corresponding set of statements are executed and program flow goes to END CASE.
ITERATIVE Constructs : Iterative constructs are used to execute a set of statements respectively. The
iterative constructs supported by PL/SQL are follows:
1) SIMPLE LOOP
2) WHILE LOOP
3) FOR LOOP
1) The Simple LOOP : It is the simplest iterative construct and has syntax like:
LOOP
Statements
END LOOP;
The LOOP does not facilitate a checking for a condition and so it is an endless loop. To end the
iterations, the EXIT statement can be used.
LOOP
<statement list>
IF condition THEN
EXIT;
END IF;
END LOOP;
The statements here is executable statements,which will be executed repeatedly until the condition
given if IF..THEN evaluates TRUE.
Page 60
Database Management System Laboratory
The condition is evaluated before each iteration of loop. If it evaluates to TRUE, sequence of statements
are executed. If the condition is evaluated to FALSE or NULL, the loop is finished and the control
resumes after the END LOOP statement.
3) THE FOR LOOP :The number of iterations for LOOP and WHILE LOOP is not known in advance.
THE number of iterations depends on the loop condition. The FOR LOOP can be used to have a definite
numbers of iterations.
1) Predefined exceptions:- Predefined exceptions are the error condition that are defined by ORACLE.
Predefined exceptions cannot be changed. Predefined exceptions correspond to common SQL errors.
The predefined exceptions are raised automatically whenever a PL/SQL program violates an ORACLE
rule.
2)User defined Exceptions:- A user defined exceptions is an error or a warning that is defined by the
program.User defined exceptions can be define in the declaration section of PL/SQL block.
User defined exceptions are declared in the declarative section of a PL/SQL block. Exceptions have a
type Exception and scope.
Syntax :
DECLARE
<Exception Name> EXCEPTION;
BEGIN
….
RAISE <Exception Name>
…
EXCEPTION
WHEN <Exception name> THEN
<Action>
END;
Exception Handling
A PL/SQL block may contain statements that specify exception handling routines. Each error or
warning during the execution of a PL/SQL block raises an exception. One can distinguish between two
types of exceptions:
Page 61
Database Management System Laboratory
System defined exceptions are always automatically raised whenever corresponding errors or warnings
occur. User defined exceptions, in contrast, must be raised explicitly in a sequence of statements using
raise <exception name>. After the keyword exception at the end of a block, user defined exception
handling routines are implemented. An implementation has the pattern
when <exception name> then <sequence of statements>;
The most common errors that can occur during the execution of PL/SQL programs are handled by
system defined exceptions. The table below lists some of these exceptions with their names and a short
description.
Page 62
Database Management System Laboratory
Syntax:-
<Exception_name>Exception;
Handling Exceptions:- Exceptions handlers for all the exceptions are written in the exception handling
section of a PL/SQL block.
Syntax:-
Exception
When exception_name then
Sequence_of_statements1;
When exception_name then
Sequence_of_statements2;
When exception_name then
Sequence_of_statements3;
End;
Example:
Declare
emp sal EMP.SAL%TYPE;
emp no EMP.EMPNO%TYPE;
too_high_sal exception;
begin
select EMPNO, SAL into emp no, emp sal
from EMP where ENAME = ‟KING‟;
if emp sal ∗1.05 > 4000 then raise too high sal
else update EMP set SQL . . .
end if ;
exception
when NO DATA FOUND – – no tuple selected
then rollback;
when too_high_sal then insert into high sal emps values(emp no);
commit;
end;
After the keyword when a list of exception names connected with or can be specified. The last when
clause in the exception part may contain the exception name others. This introduces the default
exception handling routine, for example, a rollback.
If a PL/SQL program is executed from the SQL*Plus shell, exception handling routines may contain
statements that display error or warning messages on the screen. For this, the procedure raise
application error can be used. This procedure has two parameters <error number> and <message text>.
<error number> is a negative integer defined by the user and must range between -20000 and -20999.
<error message> is a string with a length up to 2048 characters.
Page 63
Database Management System Laboratory
The concatenation operator “||” can be used to concatenate single strings to one string. In order to
display numeric variables, these variables must be converted to strings using the function to char. If the
procedure raise application error is called from a PL/SQL block, processing the PL/SQL block
terminates and all database modifications are undone, that is, an implicit rollback is performed in
addition to displaying the error message.
Example:
Lab Exercise
1) Write a PL/SQL block to calculate factorial. Use Exception Handling.
2) Write a PL/SQL block to find prime number for first 30 numbers.
3) Write a PL/SQL block to find Fibonacci series for first 50 numbers.
4) Write a PL/SQL block to find a raised to power b i.e. a b
5) Write a PL/SQL block to find the grade of a student. Enter marks for 5 subjects.
6) Write a PL/SQL block to update the table. Table: ACCT_MSTR ==> ACCT_NO CURBAL
SB1 500
7) Write on your own one PL/SQL block for the problem statement.
SB5 500
SB9 500
FAQ : SB13 500
1) What is PL/SQL? Explain.
2) What is the difference between "SQL" and "PL/SQL"?
3) What are the different Goals of PL/SQL?
4) What are exceptions? What are the different types of exceptions?
5) What are the different conditional statements used in PL/SQL?
6) What are the different iterative construct used in PL/SQL? Explain in short.
7) What are the features of PL/SQL? Explain.
8) What are the advantages of PL/SQL? Explain
9) How will you stop an infinite loop without closing the program?
10) Why PL/SQL does not support retrieving multiple records?
Page 64
Database Management System Laboratory
Assignment No. 6
Cursors: (All types: Implicit, Explicit, Cursor FOR Loop,
Title Parameterized Cursor)
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 65
Database Management System Laboratory
Assignment No: 6
Title :- 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 Cust_New with the data available in the table Cust_Old. 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 types
Page 66
Database Management System Laboratory
Page 67
Database Management System Laboratory
Implicit Cursors
PL/SQL issues an implicit cursor whenever you execute a SQL statement directly in your code, as long
as that code does not employ an explicit cursor. It is called an "implicit" cursor because you, the
developer, do not explicitly declare a cursor for the SQL statement.
If you use an implicit cursor, Oracle performs the open, fetches, and close for you automatically; these
actions are outside of your programmatic control. You can, however, obtain information about the most
recently executed SQL statement by examining the values in the implicit SQL cursor attributes.
PL/SQL employs an implicit cursor for each UPDATE, DELETE, or INSERT statement you execute in a
program. You cannot, in other words, execute these statements within an explicit
cursor, even if you want to. You have a choice between using an implicit or explicit cursor only when you
execute a single-row SELECT statement (a SELECT that returns only one row).
In the following UPDATE statement, which gives everyone in the company a 10% raise, PL/SQL
creates an implicit cursor to identify the set of rows in the table which would be affected by the update:
UPDATE employee
SET salary = salary * 1.1;
The following single-row query calculates and returns the total salary for a department. Once again,
PL/SQL creates an implicit cursor for this statement:
If you have a SELECT statement that returns more than one row, you must use an explicit cursor for
that query and then process the rows returned one at a time. PL/SQL does not yet support any kind of
array interface between a database table and a composite PL/SQL datatype such as a PL/SQL table.
Even if your query returns only a single row, you might still decide to use an explicit cursor. The
implicit cursor has the following drawbacks:
Page 68
Database Management System Laboratory
The following sections explore each of these limitations to the implicit cursor.
An explicit cursor is, at least theoretically, more efficient than an implicit cursor. An implicit cursor
executes as a SQL statement and Oracle's SQL is ANSI-standard. ANSI dictates that a single-row query
must not only fetch the first record, but must also perform a second fetch to determine if too many rows
will be returned by that query (such a situation will RAISE the TOO_MANY_ROWS PL/SQL exception).
Thus, an implicit query always performs a minimum of two fetches, while an explicit cursor only needs to
perform a single fetch.
This additional fetch is usually not noticeable, and you shouldn't be neurotic about using an implicit
cursor for a single-row query (it takes less coding, so the temptation is always there). Look out for
indiscriminate use of the implicit cursor in the parts of your application where that cursor will be
executed repeatedly. A good example is the Post-Query trigger in the Oracle Forms.
Post-Query fires once for each record retrieved by the query (created from the base table block and the
criteria entered by the user). If a query retrieves ten rows, then an additional ten fetches are needed with
an implicit query. If you have 25 users on your system all performing a similar query, your server must
process 250 additional (unnecessary) fetches against the database. So, while it might be easier to write
an implicit query, there are some places in your code where you will want to make that extra effort and
go with the explicit cursor.
If an implicit SELECT statement returns more than one row, it raises the TOO_MANY_ROWS
exception. When this happens, execution in the current block terminates and control is passed to the
exception section. Unless you deliberately plan to handle this scenario, use of the implicit cursor is a
declaration of faith. You are saying, "I trust that query to always return a single row!"
It may well be that today, with the current data, the query will only return a single row. If the nature of
the data ever changes, however, you may find that the SELECT statement which formerly identified a
single row now returns several. Your program will raise an exception. Perhaps this is what you will
want. On the other hand, perhaps the presence of additional records is inconsequential and should be
ignored.
With the implicit query, you cannot easily handle these different possibilities. With an explicit query,
your program will be protected against changes in data and will continue to fetch rows without raising
exceptions.
Lab Exercise
1) Create table with name student having the field rollno, first name, last name & branch. Insert
10 records into table. Write a PL/SQL to create a cursor to hold all the record of student table
having branch „Computer Science‟. Display all the records.
Page 69
Database Management System Laboratory
2) Write a PL/SQL block to update the record of rollno =100 & set the branch to E and TC’, if it
is not present then insert the record into the student table with the id=100; (use implicit cursor
sql%notfound).
3) Write a cursor and use it to raise the employee salaries as follows:
i) All employees of department 20 get 5% raise
ii) All employees of department 30 get 10% raise
iii) Rest of employees get 7.5% raise
Use separate cursor.
FAQ :
1) What is cursor?
2) What are the different types of cursors?
3) What are the different attributes of explicit cursor? Explain in brief.
4) What is implicit cursor?
5) Explain the FOR loop of Cursor.
6) What is difference between simple loop, while loop & for loop?
7) What is difference between Implicit & Explicit Cursor?
8) Explain FOR UPDATE cursor with an example.
9) What is CURRENT OF clause in cursor? Give an example.
10) List all predefined cursor.
Page 70
Database Management System Laboratory
Assignment No. 7
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 71
Database Management System Laboratory
Assignment No: 7
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. 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.
Page 72
Database Management System Laboratory
FUNCTION:-
A function is a subprogram, which is used to compute values. It is similar to a procedure, function also
takes arguments and can be in different modes. Function also can be stored in the database. It is a
PL/SQL block consisting of declarative, executable and exception section.
Difference between procedure and function is that the procedure call is a PL/SQL statement by itself,
while a function call is called as a part of an expression.
A function can return more than one value using OUT parameter.
A function can be called using positional or named notation.
Function_body
Where
Function_name: – is the name of the function to be created
Argument: - is the name of the function parameter
Type:- Is the data type of the associated parameter
Function_body:-Is a PL/SQL block containing code for the function.
IN:-This is default mode. The value of the actual parameter is passed into the procedure. Inside
the procedure the formal parameter is considered read only.
OUT:-Any value the actual parameter has when the procedure is called ignored. Inside the
procedure ,the formal parameters are considered as write only.
INOUT:-this mode is combination of IN and OUT
Deleting a Function:- To remove the subprogram from the database.
Syntax:-
Drop function<function_name>;
Page 73
Database Management System Laboratory
Package :
A package is a PL/SQL construct that allows related objects to be stored together. A package has 2
separate parts: the specification and the body. Each of them stored separately in the data dictionary.
Package Specification :
CREATE OR REPLACE PACKAGE package_name
{IS|AS}
type_definition|
procedure_specification |Function specification|
variable_declaration |
exception_declaration |
cursor_declaration |
pragma declaration |
end [procedure_name];
Package Body:
The package body is separate data dictionary object from the package header. It cannot be successfully
compiled unless the package header has already been successfully compiled.
Syntax:
CREATE OR REPLACE PACKAGE BODY package_name AS
Procedure definition;
Function definition;
…….
End package_name
To drop the package(both specification & the body) use the drop package command as follows:
Syntax :
Lab Exercise
1) Write a procedure on EMP table. It should increase commission of an employee. Employee
number and commission are passed as parameters to the called procedure.
2) Write a function that returns the number of employees working in a department. Pass department
number as an input to the function.
3) Create table classes with the following fields
(Deptno, course, cur_student, max_student) Insert 4 or 5 records and
Page 74
Database Management System Laboratory
Write a function which returns true if the specified class is 80 percent full or more, and false
otherwise. Write a PL/SQL block to call this function and use cursor in PL/SQL block to hold
the records of all department.
4) Write a procedure to update records of classes table and write a PL/SQL block to call that
procedure.
5) Create a package which consist of procedures for insert ,delete and update the data of classes
table.
FAQ :
1) Explain the term procedure and function of PL/SQL in short.
2) What is the difference between "procedure" and "function"?
3) What is the difference between "%type" and "%rowtype"?
4) What is package? Explain.
5) What is the use of package?
6) What are the different modes of argument passing?
7) What is difference between IN & IN OUT?
8) Write a package which consists of cursor, trigger, procedure & function.
9) What are the advantages of procedure & function?
10) Write the syntax to drop function, procedure & package.
Page 75
Database Management System Laboratory
Page 76
Database Management System Laboratory
Assignment No. 8
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 77
Database Management System Laboratory
Assignment No: 8
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.
Frame the problem statement for writing Database Triggers of all types, in-line with above
statement. The problem statement should clearly state the requirements.
Page 78
Database Management System Laboratory
Triggering time
Triggers can specify the time of trigger action.
1) Before the triggering event
The trigger action is performed before the operation that fires the trigger is executed. This trigger is
used when execution of operation depends on trigger action.
2)After the triggering event
The trigger action is performed after the operation that fires the trigger is executed.
This trigger is used when triggering action depends on the execution of operation.
Triggering Events
Triggering events are the DML operations. These operations are insert, update and delete When these
operations are performed on a table, the trigger which is associated with the operation is fired.
Triggering events divide triggers into three types.
1) DELETE TRIGGER
2) UPDATE TRIGGER
3) INSERT TRIGGER
General syntax for creation of Trigger
Create [or replace] TRIGGER <trigger_name>
<BEFORE | AFTER>
DELETE | [OR] INSERT | [OR] UPDATE[OF <column1>[,<column2>…..]
ON <table_name>
[for each row[when <condition>]
Begin
……… ………
……………….
End;
Where
Trigger_name:-trigger name is the name of the trigger.
Table_name :-is thye table name for which the trigger is defined.
Trigger-condition:-The trigger condition in the when clause,if present is evaluated first.The body
of the trigger is executed only when this condition evaluates to true.
Dropping trigger
Suppose you want to drop trigger then the syntax is
Page 79
Database Management System Laboratory
The Trigger can be disabled without dropping them. When the trigger is disabled, it is still exists in data
dictionary but never fired, To disable trigger, use alter command.
Syntax:-
Alter TRIGGER trigger_name DISABLE/ENABLE;
For all triggers on a particular table
Syntax:-
Alter TRIGGER trigger_name (DISABLE/ENABLE) all triggers;
Lab Exercise :-
1) Create a trigger that audits the operations on an Emp table.
Steps
Create table emp_audit
(id number, operation varchar2(6), Dt date, User_id number, Username varchar2(20));
If any operation like insert, update, delete done on EMP table then insert into EMP_audit table
information like the name of the operation with id, user_id and date.
2) Create a table Employee(id, Emp_name, Salary, City)
Create a trigger to convert the Emp_name into upper case before inserting or updating on
Employee table.
3) Create a trigger to check Salary is less than 20000 before inserting or updating on Employee
table.
4) Create a trigger (Statement Level Trigger) to display messages after inserting or updating or
deleting records on Employee Table.
FAQ :
Page 80
Database Management System Laboratory
Assignment No. 9
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 81
Database Management System Laboratory
Assignment No. 9
Title : Study of Open Source NOSQL Database: MongoDB (Installation, Basic
CRUD operations, Execution)
Objectives : Learn the concept of NOSQL
Theory : NOSQL
A NoSQL (originally referring to "non SQL" or "non relational") database provides a mechanism for
storage and retrieval of data that is modeled in means other than the tabular relations used in relational
databases. Such databases have existed since the late 1960s, but did not obtain the "NoSQL" moniker
until a surge of popularity in the early twenty-first century, triggered by the needs of Web 2.0
companies such as Facebook, Google, and Amazon.com. NoSQL databases are increasingly used in big
data and real-time web applications. [6] NoSQL systems are also sometimes called "Not only SQL" to
emphasize that they may support SQL-like query languages.
Motivations for this approach include: simplicity of design, simpler "horizontal" scaling to clusters of
[2]
machines (which is a problem for relational databases), and finer control over availability. The data
structures used by NoSQL databases (e.g. key-value, wide column, graph, or document) are different
from those used by default in relational databases, making some operations faster in NoSQL. The
particular suitability of a given NoSQL database depends on the problem it must solve. Sometimes the
data structures used by NoSQL databases are also viewed as "more flexible" than relational database
tables.
Many NoSQL stores compromise consistency (in the sense of the CAP theorem) in favor of availability,
partition tolerance, and speed. Barriers to the greater adoption of NoSQL stores include the use of low-
level query languages (instead of SQL, for instance the lack of ability to perform ad-hoc joins across
tables), lack of standardized interfaces, and huge previous investments in existing relational databases.
Most NoSQL stores lack true ACID transactions, although a few databases, such as MarkLogic,
Aerospike, FairCom c-treeACE, Google Spanner (though technically a NewSQL database), Symas
LMDB, and OrientDB have made them central to their designs. (See ACID and join support.)
MongoDB
MongoDB is a cross-platform, document oriented database that provides, high performance, high
availability, and easy scalability. MongoDB works on concept of collection and document.Database
Page 82
Database Management System Laboratory
Database is a physical container for collections. Each database gets its own set of files on the file
system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection
exists within a single database. Collections do not enforce a schema. Documents within a collection can
have different fields. Typically, all documents in a collection are of similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that
documents in the same collection do not need to have the same set of fields or structure, and common
fields in a collection's documents may hold different types of data.
Sample Document
Following example shows the document structure of a blog site, which is simply a comma
separated key value pair.
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [ {
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}]
}
Page 83
Database Management System Laboratory
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You can
provide _id while inserting the document. If you don‟t provide then MongoDB provides a unique id
for every document. These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for machine id,
next 2 bytes for process id of MongoDB server and remaining 3 bytes are simple incremental VALUE.
MongoDB ─ Advantages:
Any relational database has a typical schema design that shows number of tables and the relationship
between these tables. While in MongoDB, there is no concept of relationship.
Page 84
Database Management System Laboratory
Data Hub
MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list of
commands as shown in the following screenshot.
Page 85
Database Management System Laboratory
Page 86
Database Management System Laboratory
Code: This datatype is used to store JavaScript code into the document.
Regular expression: This datatype is used to store regular expression.
MongoDB ─ Insert Document
The insert() Method
To insert data into MongoDB collection, you need to use MongoDB's insert() or
save()method.
Syntax
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insert(document)
MongoDB ─ Query Document
The find() Method
To query data from MongoDB collection, you need to use MongoDB's find()method.
Syntax
The basic syntax of find() method is as follows:
>db.COLLECTION_NAME.find()
find()method will display all the documents in a non-structured way.
The pretty() Method
To display the results in a formatted way, you can use pretty() method.
Syntax
>db.mycol.find().pretty()
Apart from find() method, there is findOne() method, that returns only one document.
RDBMS Where Clause Equivalents in MongoDB
To query the document on the basis of some condition, you can use following operations
Page 87
Database Management System Laboratory
Logical operators:--
AND in MongoDB
Syntax
In the find() method, if you pass multiple keys by separating them by ',' then MongoDB
>db.mycol.find({key1:value1, key2:value2}).pretty()
OR in MongoDB
Syntax
To query documents based on the OR condition, you need to use $or keyword. Following
Example
Page 88
Database Management System Laboratory
The following example will show the documents that have likes greater than 100 and whose title is
either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL where clause is 'where likes>10
AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
{ "_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100" }
MongoDB's update()
MongoDB's update() and save() methods are used to update document into a collection. The update()
method updates the 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 the save() method.
Syntax
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA}).
Page 89
Database Management System Laboratory
MongoDB's remove() method is used to remove a 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)
If there are multiple records and you want to delete only the 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()
To limit the records in MongoDB, you need to use limit() method. The method accepts one number
type argument, which is the number of documents that you want to be displayed.
Syntax
>db.COLLECTION_NAME.find().limit(NUMBER)
Page 90
Database Management System Laboratory
Apart from limit() method, there is one more method skip() which also accepts number type argument
and is used to skip the number of documents.
Syntax
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
To sort documents in MongoDB, you need to use sort() method. The method accepts a document
containing a 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})
Page 91
Database Management System Laboratory
FAQ :
2. If you remove an object attribute, is it deleted from the database? Explain with example.
3. How does MongoDB provide consistency?
4. Define MongoDB.
5. What are the key features of mongodb?
6. Which command is use to create database? Explain with example
7. Which command is use to drop database? Explain with example
8. What is the use of pretty() method? Explain with example
9. Which method is used to remove the document form the collection? Explain with example
Page 92
Database Management System Laboratory
Assignment No. 11
Design and Develop MongoDB Queries using CRUD
Title operations. (Use CRUD operations,
SAVE method, logical operators)
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 93
Database Management System Laboratory
Assignment No. 11
Aim : Design and Develop MongoDB Queries using CRUD operations. (Use CRUD
operations, SAVE method, logical operators)
Database
Database is a physical container for collections. Each database gets its own set of files on the file
system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection
exists within a single database. Collections do not enforce a schema. Documents within a collection can
have different fields. Typically, all documents in a collection are of similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that
documents in the same collection do not need to have the same set of fields or structure, and common
fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB .
CRUD is the basic operation of Mongodb ,it stands CREATE , READ , UPDATE, DELETE.
Page 94
Database Management System Laboratory
db.createCollection(name, options)
In the command, name is name of collection to be created. Options are a document and are used to specify
configuration of collection.
Options parameter is optional, so you need to specify only the name of the collection. Following is the list of
options you can use:
While inserting the document, MongoDB first checks size field of capped collection, then it
Examples
>use test
switched to db test
>db.createCollection("mycollection")
Page 95
Database Management System Laboratory
{ "ok" : 1 }
>
You can check the created collection by using the command show collections.
>show collections
mycollection
system.indexes
Syntax
>db.COLLECTION_NAME.find()
To display the results in a formatted way, you can use pretty() method.
Syntax
>db.mycol.find().pretty()
Example
>db.mycol.find().pretty()
"_id": ObjectId(7df78ad8902c),
"url": "http://www.tutorialspoint.com",
"likes": "100"
>
Apart from find() method, there is findOne() method, that returns only one document.
Page 96
Database Management System Laboratory
3. UPDATE
MongoDB's update() and save() methods are used to update document into a collection.
The update() method updates the values in the existing document while the save() method replaces the
existing document with the document passed in save() method.
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
Example
Following example will set the new title 'New MongoDB Tutorial' of the documents whose
Tutorial'}})
>db.mycol.find()
>
By default, MongoDB will update only a single document. To update multiple documents,
>db.mycol.update({'title':'MongoDB Overview'},
Page 97
Database Management System Laboratory
save() method.
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Example
Following example will replace the document with the _id '5983548781331adf45ec7'.
>db.mycol.save(
Topic",
"by":"Tutorials Point"
})
>db.mycol.find()
"by":"Tutorials Point"}
remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
deletion criteria: (Optional) deletion criteria according to documents will be removed.
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
Page 98
Database Management System Laboratory
Following example will remove all the documents whose title is 'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find()
LOGICAL OPERATORS:
AND in MongoDB
Syntax
In the find() method, if you pass multiple keys by separating them by ',' then MongoDB
>db.mycol.find({key1:value1, key2:value2}).pretty()
Example
Following example will show all the tutorials written by 'tutorials point' and whose title is
'MongoDB Overview'.
"_id": ObjectId(7df78ad8902c),
"url": "http://www.tutorialspoint.com",
"likes": "100"
}>
For the above given example, equivalent where clause will be ' where by='tutorials point' AND title =
'MongoDB Overview' '. You can pass any number of key, value pairs in find clause.
Page 99
Database Management System Laboratory
OR in MongoDB
Syntax : To query documents based on the OR condition, you need to use $or keyword. Following
is the basic syntax of OR −
Example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB Overview'.
{ "_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100" }
Using AND and OR Together Example
The following example will show the documents that have likes greater than 100 and whose title is
either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL where clause is 'where likes>10
AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100" }
FAQ:-
1. Explain CREATE Operation with example.
2. Explain AND Operator with example.
3. Explain DELETE function in Mongodb.
4. Explain DELETE function in Mongodb.
5. Explain FIND function in Mongodb.
6. Explain OR Operator with example.
Page 100
Database Management System Laboratory
Assignment No. 12
Implement aggregation and indexing with suitable example
Title
using MongoDB.
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 101
Database Management System Laboratory
Assignment No. 12
Aim : Implement aggregation and indexing with suitable example using MongoDB.
Objectives : Learn the concept of MongoDB
Aggregations operations process data records and return computed results. Aggregation operations group
values from multiple documents together, and can perform a variety of operations on the grouped data to return a
single result. In SQL count(*) and with group by is an equivalent of mongodb aggregation.
The aggregate() Method For the aggregation in MongoDB, you should use aggregate() method.
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
Example
_id: ObjectId(7df78ad8902c)
url: 'http://www.tutorialspoint.com',
likes: 100
},
_id: ObjectId(7df78ad8902d)
Page 102
Database Management System Laboratory
url: 'http://www.tutorialspoint.com',
likes: 10
},
_id: ObjectId(7df78ad8902e)
by_user: 'Neo4j',
url: 'http://www.neo4j.com',
likes: 750
},
Now from the above collection, if you want to display a list stating how many tutorials are written by each user,
then you will use the following aggregate() method:
"result" : [
},
Page 103
Database Management System Laboratory
"_id" : "Neo4j","num_tutorial" : 1
}],
"ok" : 1
}>
Sql equivalent query for the above use case will be select by_user, count(*) from mycol group by
by_user.
Pipeline Concept
In UNIX command, shell pipeline means the possibility to execute an operation on some input and use
the output as the input for the next command and so on. MongoDB also supports same concept in
Page 104
Database Management System Laboratory
aggregation framework. There is a set of possible stages and each of those is taken as a set of
documents as an input and produces a resulting set of documents (or the final resulting JSON document
at the end of the pipeline). This can then in turn be used for the next stage and so on.
$match: This is a filtering operation and thus this can reduce the amount of documents that are given
as input to the next stage.
$skip: With this, it is possible to skip forward in the list of documents for a given amount of
documents.
$limit: This limits the amount of docu ments to look at, by the given number starting from the
current positions.
$unwind: This is used to unwind document that are using arrays. When using an array, the data is
kind of pre-joined and this operation will be undone with this to have individual documents again. Thus
with this stage we will increase the amount of documents for the next stage.
Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every
document of a collection to select those documents that match the query statement This scan is highly
inefficient and require MongoDB to process a large volume of data.
Indexes are special data structures, that store a small portion of the data set in an easy -to-traverse form.
The index stores the value of a specific field or set of fields, ordered by the value of the field as
specified in the index.
To create an index you need to use ensureIndex() method of MongoDB. The basic syntax of
ensureIndex() method is as follows().
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of the file on which you want to create index and 1 is for ascending order. To
create index in descending order you need to use -1.
Example
>db.mycol.ensureIndex({"title":1})
In ensureIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
ensureIndex() method also accepts list of options (which are optional). Following is the list:
Page 105
Database Management System Laboratory
Page 106
Database Management System Laboratory
Conclusion: - Thus we have studied use and implementation of aggregation function &indexing function.
FAQ : -
1. Enlist various aggregation operations.
Page 107
Database Management System Laboratory
Assignment No. 13
Implement Map reduces operation with suitable example
Title
using MongoDB
Roll No.
Class T.E. (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 108
Database Management System Laboratory
Assignment No. 13
Aim : Implement Map reduces operation with suitable example using MongoDB
Objectives : Learn the concept of NOSQL MongoDB
Theory :
As per the MongoDB documentation, MapReduce is a data processing paradigm for condensing large
volumes of data into useful aggregated results. MongoDB uses mapReduce command for map-reduce
operations. MapReduce is generally used for processing large data sets.
MapReduce Command
Following is the syntax of the basic mapReduce command
>db.collection.mapReduce (
function() { emit(key,value); }, //map function
function(key,values) {return reduceFunction},
{ //reduce function
out: collection,
query: document,
sort: document,
limit: number
})
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.
In the above syntax –
map is a javascript function that maps a value with a key and emits a key-value pair
reduce is a javascript function that reduces or groups all the documents having the same key
out specifies the location of the map -reduce query result
query specifies the optional selection criteria for selecting d ocuments
sort specifies the optional sort criteria
limit specifies the optional maximum number of documents to be returned Using MapReduce
Consider the following document structure storing user posts. The document stores user_name of the
user and the status of post.
{"post_text": "tutorialspoint is an awesome website for tutorials" ,
"user_name": "mark",
"status":"active" }
We will use a mapReduce function on our posts collection to select all the active posts, group them on
the basis of user_name and then count the number of posts by each user using the following code
>db.posts.mapReduce(
function() { emit(this.user_id,1); },
Page 109
Database Management System Laboratory
To see the result of this mapReduce query, use the find operator −
The above query gives the following result which indicates that both users tom
and mark have two posts in active states −
FAQ : -
1. Define and Explain mapreduce in MongoDB with examples.
4. What are NoSQL databases? What are the different types of NoSQL databases?
Page 110
Database Management System Laboratory
Assignment No. 14
Roll No.
Class T.E (E&TC)
Date
Subject Database Management System Laboratory
Signature
Page 111
Database Management System Laboratory
Assignment No. 14
Aim
Group C: Mini Project
Using the database concepts covered in Group A & Group B, develop an application with
following details:
6. Follow the same problem statement decided in Assignment -1 of Group A
7. Follow the Software Development Life cycle and other concepts learnt in Software
Engineering Course throughout the implementation.
8. Develop application considering:
Front End : Java/Perl/PHP/Python/Ruby/.net/any other language
Backend : MongoDB/MySQL/Oracle
9. Test and validate application using Manual/Automation testing
10. Student should develop application in group of 2-3 students and submit the Project Report
which will consist of documentation related to different phases of Software Development
Life Cycle:
Title of the Project, Abstract, Introduction
Software Requirement Specification
Conceptual Design using ER features, Relational Model in appropriate Normalize form
Graphical User Interface, Source Code
Testing document
Conclusion.
Note:
Instructor should maintain progress report of mini project throughout the semester from
project group
Practical examination will be on assignments given above in Group A & Group B only
Mini Project in this course should facilitate the Project Based Learning among students
Page 112