Final DBMS Lab Manual
Final DBMS Lab Manual
PO5: Modern tool Usage: Create, Select and apply appropriate techniques, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO12: Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
Program Specific Outcomes (PSOs)
PSO1: Professional Skills-The ability to understand, analyze and develop
computer programs in the areasrelated to algorithms, system software,
multimedia, web design, big data analytics, and networking for efficient
design of computer-based systems of varying complexities.
PSO2: Problem-Solving Skills- The ability to apply standard practices and
strategies in software project development using open-ended
programming environments to deliver a quality product for business
success.
PSO3: Successful Career and Entrepreneurship- The ability to employ modern
computer languages, environments and platforms in creating innovative
career paths to be an entrepreneur and to have a zest for higher studies.
CO1: Design E-R Model for given requirements and convert the same into
database tables.
CO2: Design schema in appropriate normal form considering actual
requirements. CO3: Implement SQL queries for given requirements, using
different SQL concepts. CO4: Implement PL/SQL Code block for given
requirements.
CO5: Implement NoSQL queries using MongoDB.
CO6: Design and develop application considering actual requirements and
using database concepts.
LIST OF PRACTICALS
Page
Sr No Name of the Experiments
Number
s
1 ER Modeling and Normalization
1-6
SQL Queries:
a. Design and Develop SQL DDL statements which
2 demonstrate the use of SQL objects such as Table, View,
Index, Sequence, Synonym, different constraints etc.
7-15
b. Write at least 10 SQL queries on the suitable database
application using SQL DML statements.
SQL Queries – all types of Join, Sub-Query and View:
3 Write at least10 SQL queries for suitable database application 16-24
using SQL DML statements.
Unnamed PL/SQL code block: Use of Control structure and
Exception handling is mandatory.
Suggested Problem statement:
Consider Tables:
1. Borrower(Roll_no, Name, Date of Issue, Name of Book, Status)
2. Fine(Roll_no, Date, Amt)
Accept Roll_no and Name of Book from user.
4 Check the number of days (from date of issue). 25-31
If days are between 15 to 30 then fine amount will be Rs 5per day.
If no. of days>30, per day fine will be Rs 50 per day and for
days less than 30, Rs. 5 per day. After
submitting the book, status will change from I to R.
If condition of fine is true, then details will be stored into fine
table.
Also handles the exception by named exception handler or
user define exception handler.
Named PL/SQL Block: PL/SQL Stored Procedure and
Stored Function.
Write a Stored Procedure namely proc_Grade for the
categorization of student. If marks scored by students in
examination is <=1500 and marks>=990 then student will be
5 placed in distinction category if marks scored are
between 989 and900 category is first class, if marks899and
32-37
825 category is Higher Second Class.
Write a PL/SQLblock to use procedure created with
above requirement.
Stud_Marks(name, total_marks)
Result(Roll,Name, Class)
Cursors :( All types: Implicit, Explicit, Cursor FOR Loop,
Parameterized Cursor)
Write a PL/SQL block of code using parameterized Cursor that
6 will merge the data available in the newly created 38-43
table N_Roll Call with the data available in the table O_RollCall. If
the data in the first table already exist in the
second table then that data should be skipped.
atabase Trigger (All Types: Row level and Statement level
7 triggers, Before and
After Triggers).
44-53
Write a database trigger on Library table. The System should
keep
track of the records that are being updated or
deleted. The old value of updated or deleted records should be
added in
Library_Audit table.. Student_Marks(name,
total_marks) Result(Roll,Name, Class).
Database Connectivity:
8 Write a program to implement MySQL/Oracle database
connectivity with any front end language to
54-61
implement Database navigation operations (add, delete, edit etc.)
MongoDB Queries:
9 Design and Develop MongoDB Queries using CRUD operations.
(Use CRUD operations, SAVE method, logical
62-67
operators etc.).
MongoDB – Aggregation and Indexing:
10 Design and Develop MongoDB Queries using aggregation 68-72
and indexing with suitable example using MongoDB.
MongoDB – Map-reduces operations:
11 Implement Map reduces operation with suitable example 73-76
using MongoDB.
Database Connectivity:
12 Write a program to implement MySQL/Oracle database
connectivity with any front end language to implement
77-79
Database navigation
operations (add, delete, edit etc.)
Assignment No .1
Decide a case study related to real time application in group of 2-3 students and formulate a problem statement
for application to be developed. Propose a Conceptual Design using ER features using tools like ERD plus, ER Win
etc. (Identifying entities, relationships between entities, attributes, keys, cardinalities, generalization,
specialization etc.) Convert the ER diagram into relational tables and normalize Relational data model.
Note: Student groups are required to continue same problem statement throughout all the assignments in order
to design and develop an application as a part Mini Project. Further assignments will be useful for students to
develop a backend for system. To design front end interface students should use the different concepts learnt in
the other subjects also.
Course Outcome:
C306.1 Design E-R Model for given requirements and convert the same into
Theory: -
Entity Relationship (E R) Model : The Entity Relationship (ER) model is one of several high-level, or
semantic, data models used in database design. The goal is to create a simple description of the data that
closely matches how users and developers think of the data
A database can be modeled as : a collection of entities, relationship among
entities. An Entity is real-world object that exists and is distinguishable from
other objects. A relationship is an association among several (Two or more)
entities.
Entities are represented by means of their properties, called attributes.
An entity set is a set of entities of the same type that share the same
properties. Each entity set has a Key.
Each Attribute has a Domain.
Types of Attributes
Simple attribute − Simple attributes are atomic values, which cannot be divided
further. For example, a Customer's ID number is an atomic value of 6 digits.
Composite attribute − Composite attributes are made of more than one simple attribute.
VNCOE BOTA
1
For example, a customer's complete name may have first-name, middle-initial and last
-name. Single-value attribute − Single-value attributes contain single value.
For example − Customer_ID, Social_Security_Number.
Multi-value attribute − Multi-value attributes may contain more than one
values. For example, a person can have more than one phone number,
email_address, etc.
Derived attribute − Derived attributes are the attributes that do not exist in the physical database, but
their values are derived from other attributes present in the database. For example, age can be derived
from date_of_birth
Example of ER diagram
VNCOE BOTA
2
Relational Model
The relational model is a depiction of how each piece of stored information relates to the other stored
information. It shows how tables are linked, what type of the links are between tables, what keys are used, what
information is referenced between tables. It’s an essential part of developing a normalized database structure to
prevent repeat and redundant data storage. Different types of keys: A super key is a set of one or more
attributes which; taken collectively, allow us to identify uniquely an entity in the entity set. A primary key is a
candidate key(there may be more than one) chosen by the DB designer to identify entities in an entity set. A
super key may contain extraneous attributes, and we are often interested in the smallest super key. A super key
for which no subset is a super key is called a candidate key. An entity does not posses sufficient attributes to
form a primary ket is called a weak entity set. One that does have a primary key is called a strong entity set. A
foreign key is a field in a relational table that matches the primary key column of another table. The foreign key
can be used to cross-reference tables.
Normalization
Database normalization is a technique for designing relational database tables to minimize duplication of
information and, in so doing, to safeguard the database against certain types of logical or structural problems,
namely data anomalies. In this we will write the normalization tables that is entities of “Roadway Travels.”
Normalization: In relational databases, normalization is a process that eliminates redundancy, organizes data
efficiently; Normalization is the process of efficiently organizing data in a database. There are two goals of the
normalization process: eliminating redundant data(for example, storing the same data in more than one table)
and ensuring data dependencies make sense(only storing related data in a tablet). Both of these are worthy goals
as they reduce the amt of space a database consumes and ensure that data is logically stores. The Normal Form:
the database community has developed a series of guidelines for ensuring that databases are normalized.
VNCOE BOTA
3
These are referred to as normal forms and are numbered from one ( the lowest form to
VNCOE BOTA
4
normalization, referred to as first form or INF) through five(fifth normal form of SNF). In practical applications,
you’ll often see INF, 2NF, and 3NF along with occasional 4NF. Fifth normal form is very rarely seen and won’t be
discussed in this article. It’s important to point out that they are guidelines and guidelines only. Occasionally, it
becomes necessary to stray from them to meet practical business requirements. However, when variations take
place, it’s extremely important to evaluate any possible requirements they could have on your system and
account for possible inconsistencies. That said, let’s explore the normal form.
Conclusion:
Students are able to design ER diagram and convert it into table with Normalized tables.
VNCOE BOTA
5
Activity to be Submitted by Students
4.
VNCOE BOTA
6
VNCOE BOTA
7
DBMS ThirdYear Computer
Assignment No .2
Course Objective:
Implement SQL queries for given requirements, using different SQL concepts
Course Outcome:
C306.3 Implement SQL queries for given requirements, using different SQL concepts
Theory: -
Database: - a structured set of data held in a computer, especially one that is accessible in various ways.
Database System: - A database management system (DBMS) is a computer software application that
interactswith the user, other applications, and the database itself to capture and analyze data. A general-
purpose DBMS isdesigned to allow the definition, creation, querying, update, and administration of
databases.
A database management system (DBMS) is a software tool that makes it possible to organize data in a
database.A database is a collection of information that is organized so that it can be easily accessed,
managed and updated.
=VNCOE BOTA
8
DBMS ThirdYear Computer
Setting permissions
Creating new databases
SQL is a standard programming language, but has a number of variations—including some databases’
own proprietary SQL extensions.
Top 7 open source relational databases: -
CUBRID, Firebird, MariaDB, MySQL, Postgre SQL, SQLite
RDBMS Terminology
Before we proceed to explain the MySQL database system, let us revise a few definitions related to the
database.
Database − A database is a collection of tables, with related data.
Table − A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column − One column (data element) contains data of one and the same kind, for example
the column postcode.
Row − A row (= tuple, entry or record) is a group of related data, for example the data of one
subscription.
Redundancy − Storing data twice, redundantly to make the system faster.
Primary Key − A primary key is unique. A key value can not occur twice in one table. With a key,
you can only find one row.
Foreign Key − A foreign key is the linking pin between two tables.
Compound Key − A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
Index − An index in a database resembles an index at the back of a book.
Referential Integrity − Referential Integrity makes sure that a foreign key value always
points to an existing row.
MySQL Database
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is becoming
so popular because of many good reasons −
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right. It handles a large subset of the functionality
of the most expensive and powerful database packages.
MySQL uses a standard form of the well-known SQL data language.
MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.
=VNCOE BOTA
9
DBMS ThirdYear Computer
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.
=VNCOE BOTA
10
DBMS ThirdYear Computer
MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.
Administrative MySQL Command
Here is the list of the important MySQL commands, which you will use time to time to work with MySQL
database −
USE Databasename − This will be used to select a database in the MySQL workarea.
SHOW DATABASES − Lists out the databases that are accessible by the MySQL DBMS.
SHOW TABLES − Shows the tables in the database once a database has been selected
with the use command.
SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes, key
information, whether NULL is permitted, defaults, and other information for a table.
SHOW INDEX FROM tablename − Presents the details of all indexes on the table, including
the PRIMARY KEY.
11
DBMS ThirdYear Computer
Example
Here is a simple example to connect to the MySQL server from the command
prompt − [root@host]#mysql-u root -p
Enter password:******
This will give you the mysql> command prompt where you will be able to execute any SQL command.
Following is the result of above command −
The following code block shows the result of above code −
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2854760 to server version:
5.0.9
-- Table-Level
DROP TABLE [IF EXISTS] tableName, ... CREATE
TABLE [IF NOT EXISTS] tableName (
=VNCOE BOTA
12
DBMS ThirdYear Computer
columnName columnType columnAttribute, ...
PRIMARY KEY(columnName),
FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)
=VNCOE BOTA
13
DBMS ThirdYear Computer
)
SHOW TABLES -- Show all the
tables in the default
databaseDESCRIBE|DESC tableName
-- Describe the details for a table
ALTER TABLE tableName ... -- Modify a table, e.g., ADD COLUMN and
DROP COLUMNALTER TABLE tableName ADD columnDefinition
ALTER TABLE tableName DROP columnName
ALTER TABLE tableName ADD FOREIGN KEY (columnNmae) REFERENCES
tableName (columnNmae)ALTER TABLE tableName DROP FOREIGN KEY
constraintName
SHOW CREATE TABLE tableName -- Show the CREATE TABLE statement for
this tableName
INSERT:
This is a statement is a SQL query. This command is used to insert data into the row of a
table. Syntax:
INSERT INTO students (RollNo, FIrstName, LastName) VALUES ('60', 'Tom', Erichsen');
UPDATE:
This command is used to update or modify the value of a column in the
table. Syntax:
UPDATE students
SET FirstName = 'Jhon', LastName= 'Wick'
WHERE StudID = 3;
DELETE:
This command is used to remove one or more rows from a table.
VNCOE BOTA
11
DBMS ThirdYear Computer
Set operators combine the results of two component queries into a single result.
Queries containing set operators are called compound queries. The lists of SQL
set operators are "UNION [ALL], INTERSECT, MINUS Operators".You can combine
multiple queries usingthe set operators UNION, UNION ALL, INTERSECT, and
MINUS. All set operators have
VNCOE BOTA
12
DBMS ThirdYear Computer
If component queries select character data, then the datatype of the return values
aredetermined as follows:
If both queries select values of datatype CHAR of equal length, then the
returned values have datatype CHAR of that length. If the queries select
values of CHAR with different lengths, then the returned value is VARCHAR2
with the length of the larger CHAR value.
If either or both of the queries select values of datatype VARCHAR2,
then the returned values have datatype VARCHAR2.
If component queries select numeric data, then the datatype of the return values is
determinedby numeric precedence:
If any query selects values of type BINARY_DOUBLE, then the returned values
have datatype BINARY_DOUBLE.
If no query selects values of type BINARY_DOUBLE but any query selects
values of type BINARY_FLOAT, then the returned values have datatype
BINARY_FLOAT.
If all queries select values of type NUMBER, then the returned values
have datatype NUMBER.
In queries using set operators, Oracle does not perform implicit conversion
across datatype groups. Therefore, if the corresponding expressions of
component queries resolve to both character data and numeric data, Oracle
returns an error to fetch only unique records insteadof fetching duplicate
records.
SQL functions are built into Oracle Database and are available for use in various
appropriate SQL statements. Do not confuse SQL functions with user-defined
functions written in PL/SQL.If you call a SQL function with an argument of a
datatype other than the datatype expected by the SQL function, then Oracle
attempts to convert the argument to the expected datatype before performing the
SQL function. If you call a SQL function with a null argument, then the SQL function
automatically returns null.
1. Single-Row Functions
Single-row functions return a single result row for every row of a queried table or
view. These functions can appear in
select lists, WHERE clauses, STARTWITH and CONNECT BY clauses, and HAVING
clauses.
13
DBMS ThirdYear Computer
datatypesunless otherwise documented:
VNCOE BOTA
14
DBMS ThirdYear Computer
If the input argument is CHAR or VARCHAR2, then the value returnedis VARCHAR2.
If the input argument is NCHAR or NVARCHAR2, then the value returnedis NVARCHAR2.
The length of the value returned by the function is limited by the maximum length of thedatatype
returned.
For functions that return CHAR or VARCHAR2, if the length of the return value exceeds the limit,
then Oracle Database truncates it and returns the result without an error message.
For functions that return CLOB values, if the length of the return values exceeds the limit, then
Oracle raises an error and returns no data.
3. Datetime Functions
provide a timestamp value as their argument, Oracle Database internally converts the input type toa DATE
value and returns a DATE value. The exceptions are the MONTHS_BETWEEN function,which returns a
number, and the ROUND and TRUNC functions, which do not accept timestamp or interval values at all. The
remaining datetime functions were designed to accept any of the three types of data (date, timestamp, and
interval) and to return a value of one of these types.
Conclusion:
Students are able to implement SQL queries for given requirements, using different SQL concepts
1. Write a SQL statement to create a table job_history including columns employee_id, start_date,
end_date, job_id and department_id and make sure that, the employee_id column does not contain any
duplicate value at the time of insertion and the foreign key column job_id contain only those values
which are exists in the jobs table.
+ + + + + + +
| Field | Type | Null | Key | Default | Extra |
+ + + + + + +
| JOB_ID | varchar(10) | NO | PRI | | |
| JOB_TITLE | varchar(35) | NO | | NULL | |
| MIN_SALARY | decimal(6,0) | YES | | NULL | |
| MAX_SALARY | decimal(6,0) | YES | | NULL | |
VNCOE BOTA
15
+ DBMS + + + + ThirdYear
+ Computer
+
VNCOE BOTA
16
DBMS ThirdYear Computer
2. Write a SQL statement to create a table employees including columns employee_id, first_name,
last_name, job_id, salary and make sure that, the employee_id column does not contain any duplicate
value at the time of insertion, and the foreign key column job_id, referenced by the column job_id of jobs
table, can contain only those values which are exists in the jobs table. The InnoDB Engine have been
used to create the tables. The specialty of the statement is that, The ON DELETE NO ACTION and the
ON UPDATE NO ACTION actions will reject the deletion and any updates.
3. Consider the following schema for a LibraryDatabase: BOOK (Book_id, Title, Publisher_Name, Pub_Year)
BOOK_AUTHORS (Book_id, Author_Name) PUBLISHER (Name, Address, Phone) BOOK_COPIES (Book_id,
Branch_id, No- of_Copies) BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date) LIBRARY_BRANCH
(Branch_id, Branch_Name, Address) Write SQL queries to
1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies in each branch,etc.
3. Delete a book in BOOK table. Update the contents of other tables to reflect this data manipulationoperation.
4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple query.
5. Create a view of all books and its number of copies that are currently available in the Library.
VNCOE BOTA
17
Assignment No .3
Title of Assignment: SQL Queries – all types of Join, Sub-Query and View:
Write at least10 SQL queries for suitable database application using SQL DML
statements. Note: Instructor will design the queries which demonstrate the use of
concepts like all types of Join, Sub-Query and View
Course Objective:
Implement SQL queries for given requirements, using different SQL concepts
Course Outcome:
C306.3 Implement SQL queries for given requirements, using different SQL concepts
Theory: -
Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as
single set of data. SQL Join is used for combining column from two or more tables by
using values common to both tables. Join Keyword is used in SQL queries for joining
two or more tables. Minimum required condition for joining table, is (n-1) where n, is
number of tables. A table can also join to itself known as, Self Join.
Types of Join:-
The following are the types of JOIN that we can use in SQL.
Inner
Outer
Left
Right
16
specified in the query.
Inner Join Syntax is,
SELECT column-name-
list from table-name1
INNER JOIN
table-name2
17
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and
same datatype present in both the tables to be joined.
Natural Join Syntax is,
SELECT *
from table-name1
NATURAL JOIN
table-name2;
Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
Left Outer Join
Right Outer Join
Full Outer Join
Left Outer Join
The left outer join returns a result table with the matched data of two tables then
remaining rows of the left table and null for the right table's column.
Left Outer Join syntax is,
SELECT column-name-
list from table-name1
LEFT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-
name; Left outer Join Syntax for Oracle is,
select column-
name- listfrom
table-name1, table-
name2
on table-name1.column-name = table-name2.column-name(+);
Left Outer Join query will be,
18
3 A le x
J a ihind College of E ng in eering,Kuran 3 CHENNAI
19
4 Anu Null Null
20
5 Ashish Null Null
table-name2
on table-name1.column-name = table-name2.column-
name; Right outer Join Syntax for Oracle is,
select column-
name- listfrom
table-name1, table-
name2
on table-name1.column-name(+) = table-name2.column-name;
SQL Subquery
Subquery or Inner query or Nested query is a query in a query. SQL subquery is usually
added in the WHERE Clause of the SQL statement. Most of the time, a subquery is used
when you know how to search for a value using a SELECT statement, but do not know
the exact value in the database.
Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the following SQL statements along with the comparision
operators like =, <, >, >=, <= etc.
SELECT
INSERT
UPDATE
DELETE
21
SQL Subquery Example:
22
1) Usually, a subquery should return only one record, but sometimes it can
also return multiple records when used with operators LIKE IN, NOT IN in the
where clause. The query syntax would be like,
SELECT first_name, last_name,
subject FROM student_details
WHERE games NOT IN ('Cricket', 'Football');
Subquery output would be similar to:
VNCOE BOTA
23
first_name last_name subject
Shekar Gowda
Badminton Priya Chandra
Chess
SQL Subquery; INSERT Statement
3) Subquery can be used with INSERT statement to add rows of data from one or more
tables to another table. Lets try to group all the students who study Maths in a table
'maths_group'. INSERT INTO maths_group(id, name)
SELECT id, first_name || ' ' || last_name
FROM student_details WHERE subject= 'Maths'
SQL Subquery; SELECT Statement
4) A subquery can be used in the SELECT statement as follows. Lets use the
product and order_items table defined in the sql_joins section.
select p.product_name, p.supplier_name, (select order_id from order_items where
product_id = 101) as order_id from product p where p.product_id = 101
product_name supplier_name order_id
24
use, extra or to few getting SQL error message "Incorrect syntax".
VNCOE BOTA
25
DBMS ThirdYear Computer
Conclusion:
Students are able to implement SQL queries all types of Join, Sub-Query and View for given requirements,
using different SQL concepts
VNCOE BOTA
26
DBMS ThirdYear Computer
3. From the following table, create a view for all salespersons. Return salesperson ID, name, and city.
VNCOE BOTA
27
Assignment No .4
Title of Assignment: Unnamed PL/SQL code block: Use of Control structure and Exception
handling ismandatory.
Suggested Problem statement:
Consider Tables:
1. Borrower(Roll_no, Name, Date of Issue, Name of Book, Status)
2. Fine(Roll_no, Date, Amt)
Accept Roll_no and Name of Book from user.
Check the number of days (from date of
issue).
If days are between 15 to 30 then fine amount will be Rs 5per day.
If no. of days>30, per day fine will be Rs 50 per day and for days less than 30, Rs. 5
perday. After submitting the book, status will change from I to R.
If condition of fine is true, then details will be stored into fine table.
Also handles the exception by named exception handler or user define exception handler.
OR
Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 5 to 9.
Store the radius and the corresponding values of calculated area in an empty table named areas,
consisting of two columns, radius and area.
Note: Instructor will frame the problem statement for writing PL/SQL block in line with above
statement
Course Objective:
Course Outcome:
Theory: -
A. Control Structures: - PL/SQL allows the use of an IF statement to control the execution of a
block of code. In PL/SQL, the IF -THEN - ELSIF - ELSE - END IF construct in code blocks allow
specifying certain conditions under which a specific block of code should be execute PL/SQL
Control Structures are used to control flow of execution. PL/SQL provides different kinds of
statements to provide such type of procedural capabilities. These statements are almost
same as that of provided by other languages. The flow of control statements can be
classified into the following categories:
Conditional Control
VNCOE BOTA
28
Iterative Control
Sequential Control
VNCOE BOTA
29
PL/SQL allows the use of an IF statement to control the execution of a block
of code. In PL/SQL, the IF -THEN - ELSIF - ELSE - END IF construct in code blocks allow
specifying certain conditions under which a specific block of code should be executed.
VNCOE BOTA
30
Syntax
END IF;
Iterative Control :
Simple loop : In simple loop, the key word loop should be placed before the first
statement in the sequence and the keyword end loop should be written at the end of
the sequence to end the loop.
Syntax:
Loop
End loop;
1. WHILE loop
The while loop executes commands in its body as long as the condition remains true
VNCOE BOTA
31
Syntax
The FOR loop can be used when the number of iterations to be executed are known.
Syntax :
The variable in the For Loop need not be declared. Also the increment value cannot be
specified. The For Loop variable is always incremented by 1.
3. Sequential Control :
Syntax :
GOTO jump;
....
<<jump>>
VNCOE BOTA
32
B. Exceptions
Syntax:
EXCEPTION
Predefined exception:
DUP_VAL_ON_INDEX When you try to insert a duplicate value into a unique column.
VNCOE BOTA
33
VNCOE BOTA
34
DBMS ThirdYear Computer
TOO_MANY_ROWS When a select query returns more than one row and the destination
variable can take only single value.
Syntax:
DECLARE
BEGIN
35
DBMS ThirdYear Computer
Conclusion:
Students are able to Implement PL/SQL Code block for given requirements
1. Write a PL/SQL block which accepts a cleaner number and returns the cleaners name and salary and
update this cleaner’s details by increasing salary by 10%. Use Exception Handling.
VNCOE BOTA
36
Assignment No .5
Title of Assignment: Named PL/SQL Block: PL/SQL Stored Procedure and Stored Function.
Write a Stored Procedure namely proc_Grade for the categorization of student. If marks scored by
students in examination is <=1500 and marks>=990 then student will be placed in distinction category if
marks scored are between 989 and900 category is first class, if marks899and 825 category is Higher
Second Class.
Write a PL/SQLblock to use procedure created with above
requirement. Stud_Marks(name, total_marks)
Result(Roll,Name, Class)
Note: Instructor will frame the problem statement for writing stored procedure and
Function in line with above statement.
Course Objective:
Course Outcome:
Theory: -
Stored Procedures : A stored procedure or in simple a proc is a named PL/SQL block which performs
one or more specific task. This is similar to a procedure in other programming languages. A
procedure has a header anda body. The header consists of the name of the procedure and the
parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block. A procedure is similar to
an anonymous PL/SQL Block but it is named for repeated usage.
Procedures: Passing Parameters
We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters
A procedure may or may not return any
value.General Syntax to create a
procedure is:
CREATE [OR REPLACE] PROCEDURE proc_name [list of
parameters]IS
Declaration
sectionBEGIN
37
E xecut ion
Ja ih in d College of Engineering,Kuran
section
38
EXCEPTION
Exception
sectionEND;
IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous
PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
39
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE together
the procedure is created if no other procedure with the same name exists or the existing procedure
is replaced with the current code.
Procedures: Example
The below example creates a procedure ‘employer_details’ which gives the details of the
employee. 1> CREATE OR REPLACE PROCEDURE employer_details
2> IS
3> CURSOR emp_cur IS
4> SELECT first_name, last_name, salary
FROM emp_tbl;5> emp_rec emp_cur%rowtype;
6> BEGIN
7> FOR emp_rec in
sales_cur8> LOOP
9> dbms_output.put_line(emp_cur.first_name || ' '
||emp_cur.last_name10>|| ' '
||emp_cur.salary); 11> END LOOP;
12>END;
13>
There are two ways to execute a procedure.
1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;
2) Within another procedure – simply use the procedure
name. procedure_name;
PL/SQL Functions
A function is a named PL/SQL Block which is similar to a procedure. The major difference between
a procedureand a function is, a function must always return a value, but a procedure may or may
not return a value.
General Syntax to create a function is
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
VNCOE BOTA
40
Return
return_variable;
VNCOE BOTA
41
DBMS ThirdYear Computer
EXCEPTION
exception
section Return
return_variable;
END;
1) Return Type: The header section defines the return type of the function. The return
datatype can be anyof the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype
defined in theheader section.
For example, let’s create a frunction called ''employer_details_func' similar to the one created
in stored proc1> CREATE OR REPLACE FUNCTION employer_details_func
2> RETURN VARCHAR(20);
3> IS
5> emp_name VARCHAR(20);
6> BEGIN
7> SELECT first_name INTO
emp_name 8> FROM emp_tbl WHERE
empID = '100';9> RETURN
emp_name;
10> END;
In the example we are retrieving the ‘first_name’ of employee with empID 100 to variable
‘emp_name’. The return type of the function is VARCHAR which is declared in line no 2.
The function returns the 'emp_name' which is of type VARCHAR as the return value in line no
9.A function can be executed in the following ways.
1) Since a function returns a value we can assign
it to a variable.employee_name :=
employer_details_func;
If ‘employee_name’ is of datatype varchar we can store the name of the employee by assigning the
return type ofthe function to it.
2) As a part of a SELECT statement
SELECT employer_details_func FROM dual;
3) In a PL/SQL Statements like,
VNCOE BOTA
42
DBMS ThirdYear Computer
dbms_output.put_line(employer_details_func);
This line displays the value returned by the function.
Conclusion:
1. Implement Stored Procedure to Check if a given a year is a leap year. The condition
is:- year should be (divisible by 4 and not divisible by 100) or (divisible by 4 and divisible by 400.)
Display the output on the screen using dbms_output.put_line. The year should be input by the user.
2. Implement Stored Procedure or Function to read in a number and print it out digit by digit, as a series
of words. For example, the number 523 would be printed as "five two three". Use decode function within
a for loop. Display the
results on the screen using dbms_output.put_line.
VNCOE BOTA
43
DBMS ThirdYear Computer
Assignment No .6
Title of Assignment: Cursors :( All types: Implicit, Explicit, Cursor FOR Loop, Parameterized Cursor)
Write a PL/SQL block of code using parameterized Cursor that will merge the data available in the
newly created table N_Roll Call with the data available in the table O_RollCall. If the data in the first
table already exist in the second table then that data should be skipped.
Note: Instructor will frame the problem statement for writing PL/SQL block using all types of Cursors
in line with above statement
Course Objective:
Implement PL/SQL Code block for given requirements
Course Outcome:
Theory: -
PL/SQL
Cursor
Summary: in this tutorial, we will introduce you to PL/SQL cursor. You will learn step by step how to use
a cursor to loop through a set of rows and process each row individually.
Introducing to PL/SQL Cursor
When you work with Oracle database, you work with a complete set of rows returned from an SQL
SELECT statement. However the application in some cases cannot work effectively with the entire result
set, therefore, the database server needs to provide a mechanism for the application to work with one
row or a subset of the result set at a time. As the result, Oracle created PL/SQL cursor to provide these
extensions.
A PL/SQL cursor is a pointer that points to the result set of an SQL query against
database tables. Working with PL/SQL Cursor
The following picture describes steps that you need to follow when you work with a
PL/SQL cursor:
PL/SQL Cursor
Declaring PL/SQL Cursor
DBMS ThirdYear Computer
To use PL/SQL cursor, first you must declare it in the declaration section of PL/SQL block or in a
package as fo lloJwasi :h ind College of Engineering,Kuran
cur3so8r_nam CURSOR
DBMS ThirdYear Computer
First, you declare the name of the cursor after the keyword. The name of
the cursor can have up to 30 characters in length and follows the naming rules of identifiers in
PL/SQL. It is
important to note that cursor’s name is not a variable so you cannot use it as a variable such as
assigning it to other cursor or using it in an expression. The parameter1,parameter2… are
optional elements in the cursor declaration. These parameters allow you to pass arguments
RETURN
into the cursor. The
return_specificati is also an optional part.
VNCOE BOTA
39
DBMS ThirdYear Computer
Second, you specify a valid SQL statement that returns a result set where the cursor points to.
Third, you can indicate a list of columns that you want to update after the FOR UPDATE OF. This
part is optional so you can omit it in the CURSOR declaration.
Attribute Description
Explicit Cursors
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row. We can provide a suitable name for the cursor.
General Syntax for creating a cursor is as given below:
40
DBMS ThirdYear Computer
When a cursor is opened, the first row becomes the current row. When the data is fetched it is
copied to the record or variables and the logical pointer moves to the next row and it becomes
the current row. On every fetch statement, the pointer moves to the next row. If you want to
fetch after the last row, the program will throw an error. When there is more than one row in a
cursor we can use loops along with explicit cursor attributes to fetch all the records.
FOR LOOP
CursorSyntax
The syntax for the CURSOR FOR LOOP in Oracle/PLSQL is:
FOR record_index
in
cursor_nameLOOP
{...statements...
}END LOOP;
Parameters or Arguments
record_index:The index of the
record.
cursor_name:The name of the cursor that you wish to fetch records from.
statements:The statements of code to execute each pass through the CURSOR FOR LOOP.
Parameterized cursor:
PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to
query. PL/SQL Parameterized cursor define only datatype of parameter and not need
to define its length.Default values is assigned to the Cursor parameters. and scope
of the parameters are locally.
Parameterized cursors are also saying static cursors that can passed parameter value when cursor are
opened.Following example introduce the parameterized cursor. following emp_information table,
EMP_NO EMP_NAME
1 Forbs ross
2 marks jems
3 Saulin
4 Zenia Sroll
Example Code
Cursor display employee information from emp_information table whose emp_no four (4).
Jaciuhrisnodr cC
(no
ollneug
mebeo
r)f iE
s sneg
leicnt e*efrroinmge,m
where
emp_no = no;
41
DBMS ThirdYear Computer
DECLARE
Jaciuhrisnodr cC
(no
ollneug
mebeo
r)f iE
s sneg
leicnt e*efrroinmge,m
where
emp_no = no;
42
DBMS ThirdYear Computer
tmp
emp_information%rowtype; BEGIN
OPEN c(4);
VNCOE BOTA
43
DBMS ThirdYear Computer
VNCOE BOTA
44
DBMS ThirdYear Computer
Assignment No .7
Title of Assignment: Database Trigger (All Types: Row level and Statement level triggers, Before and
AfterTriggers).
Write a database trigger on Library table. The System should keep track of the records that are being
updated or deleted. The old value of updated or deleted records should be added in Library_Audit table.
Note: Instructor will Frame the problem statement for writing PL/SQLblock for all types of Triggers in
line with above statement.
Course Objective:
Course Outcome:
PL/SQL Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.Trigger is
stored intodatabase and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some
event occurs.Triggers are written to be executed in response to any of the following
events.
o A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
o A database definition (DDL) statement (CREATE, ALTER, or DROP).
o A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated. Advantages of Triggers
These are the following advantages of Triggers:
o Trigger generates some derived column values automatically
o Enforces referential integrity
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
o Preventing invalid
transactions Creating a trigger:
Syntax for creating trigger:
1. CREATE [OR REPLACE ] TRIGGER trigger_name
2.
Ja{iB
hEinFdOR
CEol|lA
egFTER | INSTEAD OF }
e of Engineering,Kuran
45
DBMS ThirdYear Computer
3. {INSERT [OR] | UPDATE [OR] | DELETE}
46
DBMS ThirdYear Computer
4. [OF col_name]
47
DBMS ThirdYear Computer
5. ON table_name
6. [REFERENCING OLD AS o NEW AS n]
7. [FOR EACH ROW]
8. WHEN (condition)
9. DECLARE
10. Declaration-statements
11. BEGIN
12. Executable-statements
13. EXCEPTION
14. Exception-handling-statements
15. END;
Here,
o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with
the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The
INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various
DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each
row being affected. Otherwise the trigger will execute just once when the SQL statement is executed,
which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would fire. This
clause is valid only for row level triggers.
o he price of a product changes constantly. It is important to maintain the history of the
prices of the products.
o We can create a trigger to update the 'product_price_history' table when the price of the
product is updated in the 'product' table.
1) Create the 'product' table and 'product_price_history' table
CREATE TABLE
product_price_history (product_id
number(5),
48
DBMS ThirdYear Computer
supplier_name varchar2(32),
unit_price number(7,2) );
INSERT INTO
product_price_history VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price)
;
END;
/
3) Lets update the price of a product.
UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100
Once the above update query is executed, the trigger fires and updates the 'product_price_history' table.
4) If you ROLLBACK the transaction before committing to the database, the data inserted to the
,it is triggered.
49
DBMS ThirdYear Computer
table is also rolled back.
Types of PL/SQL Triggers
,it is triggered.
50
DBMS ThirdYear Computer
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement
executed. PL/SQL Trigger Execution Hierarchy
51
DBMS ThirdYear Computer
The following hierarchy is followed when a trigger is fired.
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row affected.
3) Then AFTER row level trigger fires once for each affected row. This events will alternates between
BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.
For Example: Let's create a table 'product_check' which we can use to store messages when triggers
are fired.
CREATE TABLE
product (Message
varchar2(50),
Current_Date
number(32)
);
Let's create a BEFORE and AFTER statement and row level triggers for the product table.
1) BEFORE UPDATE, Statement Level: This trigger will insert a record into the table 'product_check'
before a sql update statement is executed, at the statement level.
CREATE or REPLACE TRIGGER Before_Update_Stat_product
BEFORE
UPDATE ON product
Begin
2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table 'product_check' before
each row is updated.
CREATE or REPLACE TRIGGER
Before_Upddate_Row_product BEFORE
52
DBMS ThirdYear Computer
UPDATE ON
product FOR EACH
ROW BEGIN
53
DBMS ThirdYear Computer
INSERT INTO product_check
Values('Before update row
level',sysdate); END;
54
DBMS ThirdYear Computer
3) AFTER UPDATE, Statement Level: This trigger will insert a record into the table 'product_check'
after a sql update statement is executed, at the statement level.
CREATE or REPLACE TRIGGER
After_Update_Stat_product AFTER
UPDATE ON
product BEGIN
/
4) AFTER UPDATE, Row Level: This trigger will insert a record into the table 'product_check' after
each row is updated.
CREATE or REPLACE TRIGGER
After_Update_Row_product AFTER
insert On
product FOR
EACH ROW
BEGIN
/
Now lets execute a update statement on table product.
UPDATE PRODUCT SET unit_price =
800 WHERE product_id in (100,101);
Lets check the data in 'product_check' table to see the order in which the trigger is fired.
SELECT * FROM product_check;
Output:
Mesage Current_Date
Before update, statement 26-Nov-
55
DBMS ThirdYear Computer
57
DBMS ThirdYear Computer
1. Write pl/sql code in Trigger not to accept the existing Empno (Unique no)
2. Write pl/sql code using Trigger to salary with more than old salary
58
Assignment No .8
Course Objective:
Implement PL/SQL Code block for given requirements
Course Outcome:
C306.6
Design and develop application considering actual requirements and using database concepts
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into
native callsof the database API. It is not written entirely in
java. Advantage:
o performance upgraded than JDBC-ODBC
bridge driver.Disadvantage:
o The Native driver needs to be installed on the each client machine.
61
o The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to
be donein the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server
side. Disadvantage:
o Drivers depends on the
Database. 5 Steps to connect to the
database in javaThey are as follows:
o Register the driver class
o Creating connection
o Creating statement
o Executing queries
o Closing connection
1)Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Syntax of forName() method
1. public static void forName(String className)throws
ClassNotFoundExceptionExample to register the OracleDriver
class
1. Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with
VNCOE BOTA
62
the database.Syntax of getConnection() method
VNCOE BOTA
63
3) public static Connection getConnection(String url)throws SQLException
4) public static Connection getConnection(String url,String name,String password)
throws SQLExceptionExample to establish connection with the Oracle database
5) Connection con=DriverManager.getConnection(
6) "jdbc:oracle:thin:@localhost:1521:xe","system","password");
7) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsibleto execute queries with the database.
Syntax of createStatement() method
public Statement
createStatement()throws
SQLExceptionExample to create the statement
object Statement stmt=con.createStatement();
8) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database. This
method returns theobject of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws
SQLExceptionExample to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){ System.out.println(rs.getInt(1)+"
"+rs.getString(2));
}
9) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection. Syntax of close() method
public void close()throws
SQLExceptionExample to
close connection con.close();
import
java.sql.*;
class
OracleCon
{
public static void main(String
args[]){try{
Class.forName("oracle.jdbc.driver.OracleDriver");
K
muerm
apn");
64
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");Statement stmt=con.createStatement();
K
muerm
apn");
65
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
VNCOE BOTA
66
con.close();
}catch(Exception e){ System.out.println(e);} } }
PHP Connectivity
PHP will require that mysqli is enabled (it is on most PHP set ups).
$db =
mysqli_connect('localhost','username','password','database_na
me')or die('Error connecting to MySQL server.');
The variable $db is created and assigned as the connection string, it will be used in future steps. If
there is a failure then anerror message will be displayed on the page. If it is successful you will see
PHP connect to MySQL.
Performing a database query
The mysql query is actually performed in the body of the html page, so additional php opening and
closing tags will be required. For the query we are going to specify a read of all fields from a given
table. The $query variable selects all rows in the table. You just need to use your table name.
<?php
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying
database.');
Again the returned page in the browser should be blank and error free, if you do receive the error –
‘Error queryingdatabase..’ check the table name is correct.
<?php
//Step1
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying
database.');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
VNCOE BOTA
67
DBMS ThirdYear Computer
VNCOE BOTA
68
DBMS ThirdYear Computer
Activity to be Submitted by Students
VNCOE BOTA
69
DBMS ThirdYear Computer
VNCOE BOTA
70
Assignment No
Course Objective:
To acquire the skills to use a powerful, flexible, and scalable general-purpose databases to handle Big Data
Course Outcome:
MongoDB use DATABASE_NAME is used to create database. The command will create a new database,
if it doesn't existotherwise it will return the existing database.Syntax:
Example:If you want to create a database with name <mydb>, then use DATABASE statement would be as follows:
>use mydb
To check your currently selected database use the command db
>db;
The dropData
MongoDB db.dropDatabase() command is used to drop a existing database.
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete
default 'test' database
MongoDB Create Collection The createCollection() Method:
MongoDB db.createCollection(name, options) is used to create
collection. db.createCollection(name, options)
Syntax:
In the command, name is name of collection to be created. Options is a document and used to specify
configuration of collection
The drop() Method
MongoDB's db.collection.drop() is used to drop a collection from the database.
db.COLLECTION_NAME.drop()
71
Assignment No
Syntax:
72
To insert data into MongoDB collection, you need to use MongoDB's insert() or
Syntax
VNCOE BOTA
73
In MongoDB, the db.collection.find() method retrieves documents from a collection. The
db.collection.find() method returns a cursor to the retrieved documents. The db.collection.findOne()
method also performs a read operation to return a single document. Internally, the
db.collection.findOne() method is the db.collection.find() method with a limit of
1. Select All Documents in a Collection
An empty query document ({}) selects all documents in the collection:
db.inventory.find( {} )
Not specifying a query document to the find() is equivalent to specifying an empty query document.
Therefore thefollowing operation is equivalent to the previous operation:
db.inventory.find()
Specify Equality Condition
To specify equality condition, use the query document { <field>: <value> } to select all documents that
contain the <field> with the specified <value>. The following example retrieves from the inventory
collection all documents where the type field has the value snacks:
db.inventory.find( { type: "snacks" } )
Specify Conditions Using Query Operators
A query document can use the query operators to specify conditions in a MongoDB query.
The following example selects all documents in the inventory collection where the value of the type
field is either 'food' or'snacks':
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )
Although you can express this query using the $or operator, use the $in operator rather than the
$or operator whenperforming equality checks on the same field.
Comparison Operators and Logical Operators : For comparison of different BSON type values, see the specified
BSON comparison order.
Comparison
OperatorName
Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$in Matches any of the values specified in an array.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$nin Matches none of the values specified in an array.
Logical
Operators
Name
iN
ng
D,documents that match the conditions of both clauses.
74
Description
iN
ng
D,documents that match the conditions of both clauses.
75
$not Inverts the effect of a query expression and returns documents that do not match the query
expression.
VNCOE BOTA
76
DBMS ThirdYear Computer
$nor Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
$or Joins query clauses with a logical OR returns all documents that match the conditions of either
clause.
SAVE METHOD
The save() method has the following form:
db.collection.save( <document>, { writeConcern:
<document> })The products collection contains
the following document:
{ "_id" : 100, "item" : "water", "qty" : 30 }
The save() method performs an update with upsert:true since the document contains an
_id field:db.products.save( { _id : 100, item : "juice" } )
MongoDB Logical Query Operator - $and & $not
Logical Operator - $and
The MongoDB $and operator performs a logical AND operation on an array of two or more
expressions and retrieves the documents which satisfy all the expressions in the array. The $and
operator uses short-circuit evaluation. If the first expression (e.g. <expression1>) evaluates to false,
MongoDB will not evaluate the remaining expressions.
Syntax:
{ $and: [ { <exp1> }, { <exp2> } , ... , { <expN> } ] }
Our database name is 'myinfo' and our collection name is 'student'. Here,
is the collection bellow.Example of MongoDB Logical Operator - $and
If we want to select all documents from the collection "student" which satisfying the condition -
1. sex of student is Female and
2. class of the student is VI and
3. grd_point of the student is greater than equal to 31 the following mongodb command can be used :
>db.student.find({$and:[{"sex":"Male"},{"grd_point":{ $gte: 31 }},{"class":"VI"}]}).pretty();
Logical Operator - $not
The MongoDB $not operator performs a logical NOT operation on the given expression and fetches
selected documentsthat do not match the expression and the document that do not contain the field
as well, specified in the expression.
Syntax:
{ field: { $not: { <expression> } } }
Example of MongoDB Logical Operator - $not
If we want to select all documents from the collection "student" which satisfying the condition -age
of the student is at least 12 the following mongodb command can be used :
>db.student.find( {"age": { $not: {$lt :
VNCOE BOTA
77
DBMS ThirdYear Computer
1. Collection “orderinfo“ which contains the documents given as below(Perform on Mongo Terminal)
{
cust_id:123
cust_name:”abc”,
status:”A”,
price:250
}
i. find the average price for each customers having status 'A'
ii. Display the status of the customers whose amount/price lie between 100 and 1000
iii. Display the customers information without “_id” .
iv. create a simple index on onderinfo collection and fire the queries.
2. Collection “movies“ which contains the documents given as below(Perform on Mongo Terminal)
{
name: “Movie1”,
type: “action”,
budget:100000
0 producer:{
name:
“producer1”,
address:”PUNE”
}
}
i. Find the name of the movie having budget greater than 1,00,000.
ii. Find the name of producer who lives in Pune
iii. Update the type of movie “action” to “horror”
iv. Find all the documents produced by name “producer1” with their address
VNCOE BOTA
78
Assignment No .10
Course Outcome:
INDEXING
Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every
document of a collection to select those documents that match the query statement. This scan is
highly inefficient and requires the mongod to process a large volume of data. “Indexes are special
data structures that store a small portion of the data set in an easy to traverse form.”
The index stores the value of a specific field or set of fields, ordered by the value of the field as
specified in index.
The ensureIndex() Method
To create an index you need to use ensureIndex() method of mongodb.
SYNTAX:
Basic syntax of ensureIndex() method is as follows()
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of filed on which you want to create index and 1 is for ascending order. To
create index in descending order you need to use -1.
EXAMPLE
>db.mycol.ensureIndex({"title":1})
In ensureIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
Drop Index :
>db.mycol.dropIndex({"title":1,"description":-1})
J a i h i nd C o l leg e o f E n g i n e e r i n g , Ku r a n
the g rouped data to return a s in g l e re s u l t. I n sq l c ount(*) and with group by is an equivalent of
MongoDB
AGGREGATION :Aggregations operations process data records and return computed results.
operations on
J a i h i nd C o l leg e o f E n g i n e e r i n g , Ku r a n
the g rouped data to return a s in g l e re s u l t. I n sq l c ount(*) and with group by is an equivalent of
MongoDB
aggregation The aggregate() Method For the aggregation in mongodb you should use
method.SYNTAX: Basic syntax of aggregate() method is as follows
81
Now from the above collection if you want to display a list that how many
'tutorials point',
'tutorials point',
SQL equivalent query for the above use case will be select by_user, count(*) from mycol group by
by_user. In the above example we have grouped documents by field by_user and on each occurance
of by_user previous value of sum is incremented. There is a list available aggregation expression.
82
Now from the above collection if you want to display a list that how many
$max Gets the maximum of th db.mycol.aggregate([{$gro : {_id :
corresponding e up "$by_user",num_tutorial : {$max :
values from documents in all "$likes"}}}])
the collection.
83
DBMS ThirdYear Computer
84
DBMS ThirdYear Computer
85
Assignment No .11
Course Outcome:
Map-reduce is a data processing paradigm for condensing large volumes of data into useful
aggregated results. MongoDB uses mapReduce command for map-reduce operations. MapReduce is
generally used for processing large data sets. In simple terms, the mapReduce command takes 2
primary inputs, the mapper function and the reducer function .
Working of Mapper and Reducer Function :
MapReduce is a two-step approach to data processing. First you map, and then you reduce. The
mapping step transforms the inputted documents and emits a key=>value pair (the key and/or value
can be complex). Then, key/value pairs are grouped by key, such that values for the same key end up
in an array. The reduce gets a key and the array of values emitted for that key, and produces the final
result. The map and reduce functions are written in JavaScript. A Mapper will start off by reading a
collection of data and building a Map with only the required fields we wish to process and group
them into one array based on the key. And then this key value pair is fed into a Reducer, which will
process the values.
MapReduce Command:
syntax of the basic mapReduce command:
db.collection.mapReduce(function() {emit(key,value);}, //map
function function(key,values) {return reduceFunction}, //reduce
function
{out: collection, query: document, sort: document, limit: number})
The map-reduce function first queries the collection, then maps the result documents to emit key-
value pairs which is then reduced based on the keys that have multiple values. MapReduce
Command:
86
syntax of the basic mapReduce command:
db.co lle ction.map R educe(f unctio n()
Ja i h i n d C oll e g e o f E n g in ee{rienmgit,(Kku
ey,value);},
ran //map function
function(key,values) {return reduceFunction}, //reduce function
87
{out: collection, query: document, sort: document, limit: number}) The map-reduce function first
queries the collection, then maps the result documents to emit key-value pairs which is then reduced
based on the keys that have multiple values.
88
DBMS ThirdYear Computer
db.mapc.insert({key:”a”, value:2})
db.mapc.insert({key:”a”, value:4})
Collection “city “ which contains the documents given as below(Perform on Mongo Terminal)
89
DBMS ThirdYear Computer
city:”pune”,
type:”urban”,
state:”MH”,
population:”5600000”
90
Assignment No .12
Course Objective:
Implement PL/SQL Code block for given requirements
Course Outcome:
C306.6
Design and develop application considering actual requirements and using database concepts
Mongodb
Connectivity
Mongo
connection
Connect to MongoDB server. For MongoDB version >= 2.10.0, uses MongoClient.
// Old version, uses Mongo
Mongo mongo = new Mongo("localhost", 27017);
// Since 2.10.0, uses MongoClient
MongoClient mongo = new
MongoClient( "localhost" , 27017 );If MongoDB in
secure mode, authentication is required.
MongoClient mongoClient = new
MongoClient();DB db =
mongoClient.getDB("database
name");
boolean auth = db.authenticate("username", "password".toCharArray());
Mongo Database
Get database. If the database doesn’t exist, MongoDB will
create it for you.DB db = mongo.getDB("database name");
Display all collections from selected
database.DB db =
mongo.getDB("testdb");
Save example
Save a document (data) into a collection (table) named
BasicJDaBihOin
bjd
ecC
t doolcle
umgeento=f
91
“user”.DBCollection table = db.getCollection("user");
BasicJDaBihOin
bjd
ecC
t doolcle
umgeento=f
92
BasicDBObject();document.put("name",
"mkyong"); document.put("age", 30);
document.put("createdDate", new Date());
table.insert(document);
Update example
Update a document where
“name=mkyong”. DBCollection table
= db.getCollection("user");
BasicDBObject query = new
BasicDBObject(); query.put("name",
"mkyong");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "mkyong-updated");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
93
DBMS Lab ThirdYear Computer Engineering
table.update(query, updateObj);
Find example
Find document where “name=mkyong”, and display it with
DBCursorDBCollection table = db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
DBCursor cursor =
table.find(searchQuery);while
(cursor.hasNext()) {
System.out.println(cursor.next());
}
Delete example
Find document where “name=mkyong”, and delete it.DBCollection table =
db.getCollection("user"); BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong"); table.remove(searchQuery);
VNCOE BOTA
94