Lab Manual Database Management Systems Laboratory (310246) Te (Comp) 2019 Course
Lab Manual Database Management Systems Laboratory (310246) Te (Comp) 2019 Course
LAB MANUAL
Database Management Systems Laboratory
(310246)
TE (COMP) 2019 COURSE
Course Coordinator
Dr. Nilesh Mali
Dr.Tushar phadtare
Prof.Minal Toley
DEPARTMENT OF
COMPUTER ENGINEERING
Department of Computer Engineering
Vision: “To achieve excellence in technical and socio-economic fields.”
Mission:
M1: To develop excellent learning centers through continuous up gradation in proximity with
Academia, R&D centers and industries.
M2: To pursue research of local and global relevance.
1.
Guidelines to manual usage
This manual assumes that the facilitators are aware of collaborative learning methodologies.
This manual will provide a tool to facilitate the session on Digital Communication modules in
collaborative learning environment.
The facilitator is expected to refer this manual before the session.
Icon of Graduate Attributes
K A D I
Applying Problem Analysis Design & Investigation
Knowledge Development of problems
M E E T
Modern Tool Engineer Environment Ethics
Usage & Sustainability
Society
T O M I
Individual & Communication Project Life-Long
Team work Management Learning
& Finance
Disk Approach- Digital Blooms Taxonomy
Course Name: Database Management Systems Laboratory
Course Code: 310246
Course Outcomes: On completion of the course, learners will be able to
CO1: Design E-R Model for given requirements and convert the same into database tables.
CO2: Design schema in appropriate normal form considering actual requirements
CO3: Implement SQL queries for given requirements, using different SQL concepts
CO4: Implement PL/SQL Code block for given requirements
CO5: Implement NoSQL queries using MongoDB
CO6: Design and develop application considering actual requirements and using database concepts
CO to PO Mapping:
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 - 1 3 - 3 1 1 1 3 1 - 1
CO2 2 2 3 - 2 - 1 - 3 - 1 -
CO3 - 1 2 - 2 1 - 1 3 - - 2
CO4 - 1 2 - 2 - - - 3 2 1 -
CO5 - 1 2 - 2 - 2 - 3 1 - 1
CO6 2 2 3 - 3 1 - - 3 - 2 1
CO to PSO Mapping:
2. CO5 2 - -
CO6 3 - -
Laboratory Objective
• To develop Database programming skills
• To develop basic Database administration skills
• To develop skills to handle NoSQL database
• To learn, understand and execute process of software application development
3. Laboratory Equipment/Software
Operating System recommended: - 64-bit Open source Linux or its derivative Programming tools
recommended: - MYSQL/Oracle, MongoDB, ERD plus, ER Win
4.
Laboratory Experiment list
Sr. No Title
Prerequisite practical assignments or installation (if any)
1 Installation of Mysql Server and Client
2 Installation of MongoDB
List of Assignments
ER Modeling and Normalization
Decide a case study related to real time application in group of 2-3 students and
formulate a problem statement for application to be developed. Propose a Conceptual
1 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.
Design and Develop SQL DDL statements which demonstrate the use of SQL objects
2
such as Table, View, Index.
SQL queries for suitable database application using SQL DML statements: Insert,
3
Select, Update, delete with operators, functions, and set operator
Design at least 10 SQL queries for suitable database application using SQL DML
4
statements: all types of Join, Sub-Query and View.
5 Unnamed PL/SQL code block:
Use of Control structure and Exception handling is mandatory. Write a PL/SQL
block of code for the following requirements: -
Schema:
1 Borrower (Rollin, Name, DateofIssue, NameofBook, Status)
2 Fine(Roll_no,Date,Amt)
o Accept roll_no & name of book from user.
o Check the number of days (from date of issue), if days are between 15
to 30 then fine amount will be Rs 5per day.
o 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.
o If condition of fine is true, then details will be stored into fine table.
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
6 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)
Cursors
Write a PL/SQL block of code using parameterized Cursor that will merge the data
7 available in the newly created table N_RollCall with the data available in the table
O_RollCall. If the data in the first table already exist in the second table then that
data should be skipped.
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
8
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.
Database Connectivity
9 Write a program to implement MySQL/Oracle database connectivity with any front
end language to implement Database navigation operations (add, delete, edit etc.)
MongoDB Queries:
10 Design and Develop MongoDB Queries using CRUD operations. (Use CRUD
operations, SAVE method, logical operators etc.).
MongoDB - Map reduces operations:
11
Implement Map reduces operation with suitable example using MongoDB.
Database Connectivity:
12 Write a program to implement MongoDB database connectivity with any front end
language to implement Database navigation operations (add, delete, edit etc.)
Content Beyond Syllabus
1
2
Experiment No. 1
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.
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
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 possess sufficient attributes to form a primary key 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. These are referred to as normal forms and are numbered from one (the lowest
form to 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.
Course Outcome:
Design E-R Model for given requirements and convert the same into database tables
Design schema in appropriate normal form considering actual requirements
Experiment No. 2
Aim: Design and Develop SQL DDL statements which demonstrate the use of SQL objects such as
Table, View and Index.
Objective:
1. Creating Tables using MySQL database
2. Creating View using MySQL database
3. Creating Index and Sequence on tables
4.Creating Synonym
Field Attribute NOT NULL is being used because we do not want this field to be NULL.
So, if a user will try to create a record with a NULL value, then MySQL will raise an
error.
Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next
available number to the id field.
Keyword PRIMARY KEY is used to define a column as a primary key. You can use
multiple columns separated by a comma to define a primary key.
// The newly created table newEmployee1 will include all the field and records as in Employee table
2) Creating Table having specific field but all the records from existing table
Syntax:
For example:
B) Modifying Table
ALTER TABLE query is used to modify structure of a table which is already exists in the
database. We can add, delete, or modify column
1) Adding new column in a
table Syntax:
ALTER TABLE table_name ADD Columan-name datatype;
For example
4) Renaming Table
Syntax: rename table current_table to new_table_name;
2) Creating view having specific fields but all the records from
existing table Syntax:
Create or replace view view_name as
Select field1,field2… from existing_table_name;
B) Updating View
Updating query is used to update the records of view. Updation in view reflects the original table
also.
Syntax:
UPDATE view_name
Set field_name=new_Value where condition;
C)Dropping View
Syntax: DROP view view_name
B) Displaying Index
To display index information regarding table following query is used
Syntax: show index from table_name;
Show index from Emp;
C) Dropping Index
To drop index of a table following query is
used Syntax: Drop index index_name on
table_name;
Drop index emp1_ind1 on emp;
DDL Commands of Sequence:
A Sequence is a set of integers. Sequences are generated in order as per requirements.Sequences are
used to create unique values for the rows.
Create table emp2(empno int auto_increment,ename varchar(10),sal int, primary key(empno));
DDL Commands on Synonym
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects. You generally use synonyms when you are granting
access to an object from another schema and you don't want the users to have to worry about
knowing which schema owns the object.
Syntax: In Oracle the commands is as follows
create synonym Cutomers for LongTablePrefix_Customers;
Program:
//Create Table
mysql> use dbms;
Database changed
mysql> create table Employee(
-> employee_no INT NOT NULL AUTO_INCREMENT,
-> employee_name varchar(10) NOT NULL,
-> joining_date DATE,
-> salary INT,
-> PRIMARY KEY(employee_no)
-> );
Query OK, 0 rows affected (0.34 sec)
1)Creating Table from Existing Table
mysql> Create table newEmployee1 as select * from
Employee; Query OK, 0 rows affected (0.37 sec)
Records: 0 Duplicates: 0 Warnings: 0
2)Creating Table having specific field but all the records from existing table
4) Renaming Table
Creating Index
mysql> create table emp(empno int,name varchar(7),salary
int); Query OK, 0 rows affected (0.32 sec)
mysql>
Creating Sequence
Conclusion:
In this way, we developed SQL DDL statements which demonstrate the use of SQLobjects such as
Table, view, Index, Sequence, Synonym.
Outcome:
Implement SQL queries for given requirements, using different SQL concepts
Experiment No. 3
Title: SQL queries for suitable database application using SQL DML statements: Insert, Select, Update,
delete with operators, functions, and set operator
Objective:
To list and understand DML commands and SQL Set Operations and functions
Use database techniques such as SQL DML statements
Software Required: MySQL
Theory:
DML command
Data Manipulation Language (DML) statements are used for managing data in database. DML
commands are not auto-committed. It means changes made by DML command are not permanentto
database, it can be rolled back.
1) INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
101 Adam 15
2) UPDATE command
Update command is used to update a row of a table. Following is its general syntax,
3) Delete command
Delete command is used to delete data from a table. Delete command can also be used withcondition
to delete a particular row. Following is its general syntax,
DELETE from table-name;
Example to Delete all Records from a Table
DELETE from Student;
The above command will delete all the records from Student table.
SQL Functions
SQL provides many built-in functions to perform operations on data. These functions are useful
while performing mathematical calculations, string concatenations, sub-strings etc. SQL functions
are divided into two catagories,
• Aggregrate Functions
• Scalar Functions
Aggregrate Functions
These functions return a single value after calculating from a group of values.Following are some
frequently used Aggregrate functions.
1) AVG()
Average returns average value after calculating from values in a numeric column.Its
general Syntax is,
SELECT AVG(column_name) from table_namee.g.
SELECT avg(salary) from Emp;
2) COUNT()
Count returns the number of rows present in the table either based on some condition or without
condition.
Its general Syntax is,
SQL query
SELECT FIRST(salary) from Emp;
4) LAST()
LAST return the return last value from selected column
Syntax of LAST function is,
SELECT LAST(column_name) from table-name
5) MAX()
MAX function returns maximum value from selected column of the table.
Syntax of MAX function is,
SELECT MAX(column_name) from table-name
6) MIN()
MIN function returns minimum value from a selected column of the table.Syntax for
MIN function is,
SELECT MIN(column_name) from table-name
7) SUM()
SUM function returns total sum of a selected columns numeric values.
Syntax for SUM is,
SELECT SUM(column_name) from table-nameSQL
query to find sum of salaries will be, SELECT
SUM(salary) from emp;
Scalar Functions
Scalar functions return a single value from an input value. Following are soe frequently usedScalar
Functions.
1) UCASE()
UCASE function is used to convert value of string column to Uppercase character.
Syntax of UCASE,
SELECT UCASE(column_name) from table-name
Example of UCASE()
SQL query for using UCASE is,
2) LCASE()
LCASE function is used to convert value of string column to Lowecase character.
3) MID()
MID function is used to extract substrings from column values of string type in a table.
4) ROUND()
ROUND function is used to round a numeric field to number of nearest integer. It is used on
Decimal point values. Syntax of Round function is,
SELECT ROUND(column_name, decimals) from table-name
Operators:
AND and OR operators are used with Where clause to make more precise conditions for fetching
data from database by combining more than one condition together.
1) AND operator
AND operator is used to set multiple conditions with Where clause.
Example of AND
SELECT * from Emp WHERE salary < 10000 AND age > 25
2) OR operator
OR operator is also used to combine multiple conditions with Where clause. The only difference
between AND and OR is their behavior. When we use AND to combine two or more than two
conditions, records satisfying all the condition will be in the result. But in case of OR, atleast one
condition from the conditions specified must be satisfied by any record to be in the result.
Example of OR
Example of UNION
select * from First
UNION
4) Union All
This operation is similar to Union. But it also shows the duplicate rows.
UNION ALL
5) Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records
which are common from both SELECT statements. In case of Intersect the number of columnsand
datatype must be same. MySQL does not support INTERSECT operator.
Conclusion: Hence we studied the DML commands and SQL set operators
OUTCOMES:
Students will be able to write queries for given requirements, using SQL DML Commands
Students will be able to write queries for given requirements, using SQL Set Operations and functions
Experiment No. 4
Title:
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
Objective:
Implement SQL queries for given requirements, using different SQL concepts
Software Required: - Mysql
Theory: -
Join in SQL
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of data.
SQL Join is used for combining column from two or more tables by using values common to both tables.
Join Keyword is used in SQL queries for joining two or more tables. Minimum required condition for
joining table, is (n-1) where n, is number of tables. A table can also join to itself known as, Self Join.
Types of Join:-
The following are the types of JOIN that we can use in SQL.
Inner
Outer
Left
Right
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 comparisons operators like =,
<, >, >=, <= etc.
SELECT
INSERT
UPDATE
DELETE
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:
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
Correlated Subquery
A query is called correlated subquery when both the inner query and the outer query are interdependent.
For every row processed by the inner query, the outer query is processed as well. The inner query
depends on the outer query before it can be processed.
SELECT p.product_name FROM product p
WHERE p.product_id = (SELECT o.product_id FROM order_items o WHERE o.product_id =
p.product_id);
Non-Correlated Subquery
2) If a subquery is not dependent on the outer query it is called a non-correlated subquery
Subquery Errors
3) Minimize subquery errors: Use drag and drop, copy and paste to avoid running subqueries with
spelling and database typos. Watch your multiple field SELECT comma use, extra or to few getting SQL
error message "Incorrect syntax".
SQL Subquery Comments
Adding SQL Subquery comments are good habit (/* your command comment */) which can save you
time, clarify your previous work. results in less SQL headaches.
SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or more tables can be
seen. Views do not contain data of their own. They are used to restrict access to the database or to hide
data complexity. A view is stored as a SELECT statement in the database.
DML operations on a view like INSERT, UPDATE, DELETE affects the data in the original table upon
which the view is based.
The Syntax to create a sql view is
CREATE VIEW view_name AS
SELECT column_list
FROM table_name [WHERE condition];
view_name is the name of the VIEW.
The SELECT statement is used to define the columns and rows that you want to display in the view.
For Example: to create a view on the product table the sql query would be like, CREATE VIEW
view_product
AS SELECT product_id, product_name FROM product;
Conclusion:
Students are able to implement SQL queries all types of Join, Sub-Query and View for given
Outcome:
C310246.3 Implement SQL queries for given requirements, using different SQL concepts
requirements, using different SQL concepts
Experiment No. 5
Title: Unnamed PL/SQL code block: Use of Control structure and Exception handling is
mandatory. Write a PL/SQL block of code for the following requirements: -
Schema:
Borrower(Rollin, Name, DateofIssue, NameofBook, Status)
Fine(Roll_no,Date,Amt)
Accept roll_no & name of book from user.
Check the number of days (from date of issue), if days are between 15 to 30 then
fineamount 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
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.
Ojective: Upon Completion of this assignment students should able to learn
2. Operation using PL/SQL block like Control structure and Exception Handling.
Theory:
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database. Following are certain
notable facts about PL/SQL −
PL/SQL is a completely portable, high-performance transaction-processing language.
PL/SQL provides a built-in, interpreted and OS independent programming environment.
PL/SQL can also directly be called from the command-line SQL*Plus interface.
Direct call can also be made from external programming language calls to database.
PL/SQL's general syntax is based on that of ADA and Pascal programming language.
Apart from Oracle, PL/SQL is available in TimesTen in-memory database and
IBM DB2. Features of PL/SQL
PL/SQL has the following features −
PL/SQL is tightly integrated with SQL.
It offers extensive error checking.
It offers numerous data types.
It offers a variety of programming structures.
It supports structured programming through functions and procedures.
It supports object-oriented programming.
It supports the development of web applications and server
pages.
The PL/SQL programs are divided and written in logical blocks of code. Each block consists of
three sub-parts −
S.No Sections &
Description
Declarations
1 This section starts with the keyword DECLARE. It is an optional section and
defines all variables, cursors, subprograms, and other elements to be used in the
program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a
2 mandatory section. It consists of the executable PL/SQL statements of the program.
It should have at least one executable line of code, which may be just a NULL
command to indicate that nothing should be executed.
Exception Handling
3 This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within
other PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL
block −
DECLARE
<declarations section>
BEGIN
The 'Hello
<executable World' Example
command(s)>
EXCEPTION
DECLARE
<exception handling>
message varchar2(20):= 'Hello, World!';
END; The end; line signals the end of the PL/SQL block. To run the code from the SQL command
BEGIN
line, you may need to type / at the beginning of the first blank line after the last line of the
dbms_output.put_line(message);
END; code. When the above code is executed at the SQL prompt, it produces the following result −
/
Scalar
1 Single values with no internal components, such as a NUMBER, DATE, or
BOOLEAN.
Large Object (LOB)
2 Pointers to large objects that are stored separately from other data items, such as
text, graphic images, video clips, and sound waveforms.
Composite
3 Data items that have internal components that can be accessed individually. For
example, collections and records.
Reference
4 Pointers to other data items.
Numeric
1 Numeric values on which arithmetic operations are performed.
Character
2 Alphanumeric values that represent single characters or strings of characters.
Boolean
3
Logical values on which logical operations are performed.
Datetime
4 Dates and times.
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype
called INTEGER. You can use the subtypes in your PL/SQL program to make the data types
compatible with data types in other programs while embedding the PL/SQL code in another
program, such as a Java program.
PL/SQL Numeric Data Types and Subtypes
Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −
S.No Data Type & Description
PLS_INTEGER
1 Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
BINARY_INTEGER
2 Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
BINARY_FLOAT
3 Single-precision IEEE 754-format floating-point number
BINARY_DOUBLE
4 Double-precision IEEE 754-format floating-point number
NUMBER(prec, scale)
5 Fixed-point or floating-point number with absolute value in range 1E-130 to
(but not including) 1.0E126. A NUMBER variable can also represent 0
DEC(prec, scale)
6 ANSI specific fixed-point type with maximum precision of 38 decimal digits
DECIMAL(prec, scale)
7 IBM specific fixed-point type with maximum precision of 38 decimal digits
NUMERIC(pre, secale)
8 Floating type with maximum precision of 38 decimal digits
DOUBLE PRECISION
9 ANSI specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)
10 FLOAT
ANSI and IBM specific floating-point type with maximum precision of 126 binary
digits (approximately 38 decimal digits)
INT
11 ANSI specific integer type with maximum precision of 38 decimal digits
INTEGER
12 ANSI and IBM specific integer type with maximum precision of 38 decimal digits
SMALLINT
13 ANSI and IBM specific integer type with maximum precision of 38 decimal digits
REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately 18
decimal digits)
Following is a valid declaration −
DECLARE
num1
WhenINTEGER;
the above code is compiled and executed, it produces the following result −
num2 REAL;
PL/SQL procedure successfully completed
num3 DOUBLE
PRECISION;
PL/SQL BEGIN
Character Data Types and Subtypes
null;
Following is the detail of PL/SQL pre-defined character data types and their sub-types −
END;
/ S.No Data Type & Description
CHAR
1 Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2
2 Variable-length character string with maximum size of 32,767 bytes
RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not
interpreted by PL/SQL
NCHAR
4 Fixed-length national character string with maximum size of 32,767 bytes
NVARCHAR2
5 Variable-length national character string with maximum size of 32,767 bytes
LONG
6 Variable-length character string with maximum size of 32,760 bytes
LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not
interpreted by PL/SQL
ROWID
8 Physical row identifier, the address of a row in an ordinary table
UROWID
9 Universal row identifier (physical, logical, or foreign row identifier)
PL/SQL Boolean Data Types
The BOOLEAN data type stores logical values that are used in logical operations. The logical
values are the Boolean values TRUE and FALSE and the value NULL.
However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be
used in
−
SQL statements
Built-in SQL functions (such as TO_CHAR)
PL/SQL functions invoked from SQL
statements Variable Declaration in PL/SQL
PL/SQL variables must be declared in the declaration section or in a package as a global
variable. When you declare a variable, PL/SQL allocates memory for the variable's value and
the storage location is identified by the variable name.
The syntax for declaring a variable is −
counter binary_integer := 0;
greetings
You canvarchar2(20)
also specifyDEFAULT 'Haveshould
that a variable a Good
notDay';
have a NULL value using the NOT NULL
constraint. If
you use the NOT NULL constraint, you must explicitly assign an initial value for that variable.
It is a good programming practice to initialize variables properly otherwise, sometimes programs
would produce unexpected results. Try the following example which makes use of various types of
variables −
DECLARE
a When
integer :=
the above code is executed, it produces the following result −
10; b integer
Value
:= of20; c: 30 c
integer;
Value of f: 23.333333333333333333
Variable Scope in PL/SQL
f
PL/SQL
PL/SQL
real; allows the
procedure nesting ofcompleted.
successfully blocks, i.e., each program block may contain another inner block.
BEGIIf a variable is declared within an inner block, it is not accessible to the outer block. However, if
N
c a:=variable
a + b; is declared and accessible to an outer block, it is also accessible to all nested inner
dbms_output.put_line('Value
blocks. There are two types of of variable
c: ' || scope −
) f 70 0/3 0
Local variables − Variables declared in an inner block and not accessible to outer blocks.
CREATE TABLE
CUSTOMERS(
Let us now insert ID some
INT NOTvalues in the table −
NULL,
INSERT
NAME INTOVARCHAR CUSTOMERS
(20) NOT(ID,NAME,AGE,ADDRESS,SALARY)
NULL,
VALUES AGE INTprogram
NOT32,
(1, 'Ramesh',
The following NULL,
'Ahmedabad',
assigns values2000.00 ); above table to PL/SQL variables using the
from the
ADDRESS CHAR (25),
SELECT
SALARY
INSERT INTODECIMAL
CUSTOMERS (18, 2),
(ID,NAME,AGE,ADDRESS,SALARY)
PRIMARY KEY
INTO clause of SQL −(ID) VALUES (2, 'Khilan',
25,
); 'Delhi', 1500.00 );
DECLARE
c_id customers.id%type
INSERT INTO CUSTOMERS := 1;
/(ID,NAME,AGE,ADDRESS,SALARY)
c_name VALUES (3, 'kaushik',
When
'Kota',the above );code is executed, it produces the following result −
customerS.No.ame%type;
23, 2000.00
c_addr customers.address%type;
Customer Ramesh from Ahmedabad earns 2000
c_sal customers.salary%type;
INSERT INTO CUSTOMERS
Basic
BEGIN loop structure encloses sequence
(ID,NAME,AGE,ADDRESS,SALARY) VALUES of(4,statements
'Chaitali', in between the LOOP and END
PL/SQL procedure completed successfully
SELECT
25, 'Mumbai',
LOOP name, address,
6500.00
statements. ); salary
With each INTO c_name,
iteration, c_addr, of statements is executed and then control
the sequence
c_sal FROM customers
resumes
WHERE
INSERT at =
id
INTO thec_id;
top of the loop.
CUSTOMERS
dbms_output.put_li
Syntax
The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence
Here, theofsequence of statement(s) may be a single statement or a block of statements. An
statements;
EXIT
statement or an EXIT WHEN statement is required to break
the loop.Example
DECLARE
x When
number the:=above code is executed at the SQL prompt, it produces the following result −
10; BEGIN
10LOOP
20 You
dbms_output.put_line(x);
can use the EXIT WHEN statement instead of the EXIT statement −
30 x := x + 10;
40 IF x > 50 THEN
50 exit;
AfterEND
Exit x is: 60
IF;
PL/SQLEND procedure successfully completed
LOOP;
DECLARE
x number :=
END LOOP;
10; BEGIN
--When
after exit, control resumes here
LOOP the above code is executed at the SQL prompt, it produces the following result −
dbms_output.put_line('After Exit x is: ' ||
dbms_output.put_line(x);
10x);
x := x + 10;
20
END;A WHILE
exit WHENLOOPx > 50;statement in PL/SQL programming language repeatedly executes a target
30
40 statement
50long as a given condition is true.
as
After Exit x is: 60
Syntax
PL/SQL procedure successfully completed
WHILE condition LOOP
sequence_of_statements
Example
END LOOP;
DECLARE
a When
number(2) := code is executed at the SQL prompt, it produces the following result −
the above
10;BEGIN
value
WHILEof a:a10< 20 LOOP
dbms_output.put_line('value
A FOR
value LOOP is a repetitionofcontrol
of a: 11 a: ' || structure that allows you to efficiently write a loop that
a); a := a + 1;
value of a:to12
needs
END
value
LOOP;ofaa: 13
execute specific number of times.
END; of a: 14
value
value of a: 15
value of a: 16
Syntax
value of a: 17
value of a: 18IN initial_value .. final_value LOOP
FOR counter
sequence_of_statements;
END LOOP; is the flow of control in a For Loop −
Following
The initial step is executed first, and only once. This step allows you to declare and
initialize any loop control variables.
Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the body
of the loop is executed. If it is FALSE, the body of the loop does not execute and the
flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the value of the counter variable is increased or
decreased.
The condition is now evaluated again. If it is TRUE, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes FALSE, the FOR-LOOP terminates.
Following are some special characteristics of PL/SQL for loop −
The initial_value and final_value of the loop variable or counter can be literals,
variables, or expressions but must evaluate to numbers. Otherwise, PL/SQL raises the
predefined exception VALUE_ERROR.
The initial_value need not be 1; however, the loop counter increment (or decrement)
must be 1.
PL/SQL allows the determination of the loop range dynamically at
run time. Example
DECLARE
a When
number(2);
the above code is executed at the SQL prompt, it produces the following result −
BEGIN
value
FORofa a:
in 10
10 .. 20 LOOP
dbms_output.put_line('value
Reverse
value FOR
of a: LOOP
11 Statement of a: ' || a);
END LOOP;
value
Byofdefault,
a: 12 iteration proceeds from the initial value to the final value, generally upward from
END;
value
/ theoflower
a: 13
bound to the higher bound. You can reverse this order by using the REVERSE
value of a: 14
keyword. In such case, iteration proceeds the other way. After each iteration, the loop counter is
value of a: 15
decremented.
value of a: 16
Theofsyntax
value a: 17 for a nested basic LOOP statement in PL/SQL is as follows −
value
LOOPof a: 18
value of a: 19
Sequence of
statements1 LOOP
The syntaxoffor a nested FOR LOOP statement in PL/SQL is as follows –
Sequence
statements2 END
LOOP;
FOR counter1 IN initial_value1 .. final_value1
LOOP sequence_of_statements1
FOR counter2 IN initial_value2 .. final_value2
The
LOOPsyntax for a nested WHILE LOOP statement in Pascal is as follows –
sequence_of_statements2
END
LOOP;
WHILE condition1
LOOP
sequence_of_statements
The1Loop
WHILEControl Statements
condition2
LOOP
Loop control statements change execution from its normal sequence. When execution leaves a
sequence of statements2
scope, all automatic objects that were created in that scope are destroyed.
PL/SQL supports the following control statements. Labeling loops also help in taking the
control outside a loop. Click the following links to check their details.
S.No Control Statement &
Description
EXIT statement
1 The Exit statement completes the loop and control passes to the statement
immediately after the END LOOP.
2 CONTINUE statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
GOTO statement
3 Transfers control to the labeled statement. Though it is not advised to use the
GOTO statement in your program.
An exception is an error condition during a program execution. PL/SQL supports programmers
to catch such conditions using EXCEPTION block in the program and an appropriate action is
taken against the error condition. There are two types of exceptions −
System-defined exceptions
User-defined
exceptions Syntax for Exception
Handling
The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others THEN
−
DECLARE
<declarations
section> BEGIN
Example
<executable
command(s)>
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had
EXCEPTION
created andhandling
<exception used in the
goesprevious
here > chapters −
WHEN exception1 THEN
DECLARE
exception1-handling-
c_id customers.id%type := 8; c_name
END; /
statements
customerS.No.ame%type; c_addr
customers.address%type;
WHEN exception2 THEN
When the above code is executed at the SQL prompt, it produces the following result −
BEGIN
exception2-handling-
SELECT name, address INTO c_name, c_addr FROM customers
No such customer!
statements
WHERE id = c_id;
WHEN exception3 THEN('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE
PL/SQL procedure successfully
exception3-handling-
DBMS_OUTPUT.PUT_LINE completed.
('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN dbms_output.put_line('No such
customer!');
WHEN others THEN
dbms_output.put_line('Error!');
The above program displays the name and address of a customer whose ID is given. Since there
is no
customer with ID value 8 in our database, the program raises the run-time
exception NO_DATA_FOUND, which is captured in the EXCEPTION block.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
DECLARE
exception_name
database error,EXCEPTION;
but exceptions can be raised explicitly by the programmer by using the
BEGIN
IFcommand RAISE. Following is the simple syntax for raising an exception −
condition THEN
RAISE exception_name;
YouIF;can use the above syntax in raising the Oracle standard exception or any user-defined
END
EXCEPTION
exception. In
WHEN exception_name THEN
the next section, we will give you an example on raising a user-defined exception. You can raise
statement;
END;
the Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user- defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID, when the
DECLARE
c_id
usercustomers.id%type
enters an invalid ID,:=the&cc_id;
exception invalid_id is raised.
c_name customerS.No.ame%type;
WHERE
c_addr id = c_id;
customers.address%type;
--When
user the
defined
aboveexception
DBMS_OUTPUT.PUT_LINEcode is executed ('Name: '||
at the SQL prompt, it produces the following result −
ex_invalid_id
c_name); DBMS_OUTPUT.PUT_LINE
Enter value for' ||cc_id:
EXCEPTION;
('Address: -6 (let's enter a
c_addr);
value
END-6)
BEGIN old 2: c_id customers.id%type :=
IF;
&cc_id;
IF c_idnew
<= 02:THENc_id customers.id%type
Program:
:= -6;
EXCEPTION
RAISE
IDWHEN
must
ex_invalid_id;
be
DECLARE greater than THEN
ex_invalid_id zero!
ELSE
dbms_output.put_line('ID must be greater than zero!');
Roll_No
WHENNUMBER;
no_data_found THEN
dbms_output.put_line('No
BookName varchar2(50); such
customer!');
IssueDate
WHEN DATE;
others THEN
CurrentDate DATE;
NoOfDays Number(2);
Fine Number;
BEGIN
DBMS_OUTPUT.PUT_LINE('Enter Student Roll
Number'); Roll_No := &rollno;
DBMS_OUTPUT.PUT_LINE('Enter Book
Name'); BookName := &bookname;
CurrentDate := trunc(SYSDATE);
SELECT DateOfIssue into IssueDate FROM Borrower WHERE RollNo = Roll_No AND NameOfBook
=BookName;
SELECT trunc(SYSDATE) - IssueDate INTO NoOfDays from
dual;DBMS_OUTPUT.PUT_LINE('No of Days' || NoOfDays);
IF (NoOfDays > 30) THEN
Fine := NoOfDays * 50;
ELSIF (NoOfDays >= 15 AND NoOfDays <=30) THEN
Fine := NoOfDays * 5;
END IF;
IF FINE > 0 THEN
INSERT INTO Fine values (Roll_No, CurrentDate,
Fine); END IF;
UPDATE Borrower SET Status = 'R' WHERE
RollNo=Roll_No;END;
Conclusion: Thus we have studied how to write pl/sql code block with the help of control structures
and exception handling.
Outcome:
Students will be able define, declare, initialize and manage variable values.
Students will be able to write and execute PLSQL unnamed blocks and use control structures.
Students will be able to manage errors with exception handling
Experiment No. 6
Title of Assignment:
Named PL/SQL Block: PL/SQL Stored Procedure and Stored Function.
Write a Stored Procedure namely proc_Grade for the categorization of student. If marks scored by
students in examination is <=1500 and marks>=990 then student will be placed in distinction category if
marks scored are between 989 and900 category is first class, if marks899and 825 category is Higher
Second Class.
Write a PL/SQLblock to use procedure created with above requirement.
Stud_Marks(name, total_marks)
Result (Roll,Name, Class)
Note: Instructor will frame the problem statement for writing stored procedure and Function in
line with above statement.
Course Objective:
Implement PL/SQL Code block for given requirements
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 and a body. The header consists of the name of the procedure and the parameters or variables
passed to the procedure. The body consists or declaration section, execution section and exception
section similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it
is named for repeated usage.
Procedures: Passing Parameters
We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters
A procedure may or may not return any value. General Syntax to create a procedure is:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS
Declaration section BEGIN
Execution section
EXCEPTION
Exception section END;
IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous
PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE together
the procedure is created if no other procedure with the same name exists or the existing procedure is
replaced with the current code.
Procedures: Example
The below example creates a procedure ‘employer_details’ which gives the details of the employee.
PL/SQL Functions
A function is a named PL/SQL Block which is similar to a procedure. The major difference between a
procedure and a function is, a function must always return a value, but a procedure may or may not
return a value.
General Syntax to create a function is
CREATE [OR REPLACE] FUNCTION function_name [parameters] RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section Return return_variable; END;
1) Return Type: The header section defines the return type of the function. The return datatype can be
any of the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype defined in the
header section.
For example, let’s create a frunction called ''employer_details_func' similar to the one created in stored
proc
CREATE OR REPLACE FUNCTION employer_details_func
RETURN VARCHAR(20);
IS
emp_name VARCHAR(20);
BEGIN
SELECT first_name INTO emp_name 8> FROM emp_tbl WHERE empID = '100'; 9> RETURN
emp_name;
END;
In the example we are retrieving the ‘first_name’ of employee with empID 100 to variable ‘emp_name’.
The return type of the function is VARCHAR which is declared in line no 2.
The function returns the 'emp_name' which is of type VARCHAR as the return value in line no 9. A
function can be executed in the following ways.
1) Since a function returns a value we can assign it to a variable. employee_name :=
employer_details_func;
If ‘employee_name’ is of datatype varchar we can store the name of the employee by assigning the
return type of the function to it.
2) As a part of a SELECT statement
dbms_output.put_line(employer_details_func);
This line displays the value returned by the function.
Program
-- Result table
create table Result(
STUD_NAME varchar2(20),
ROLL_NO number(5),
CLASS varchar2(20)
);
BEGIN
FOR i IN (SELECT * FROM Stud_Marks)
LOOP
DBMS_OUTPUT.PUT_LINE('Student Name: ' || i.Stud_Name || ' Student Marks: ' ||
i.Total_Marks);
IF i.Total_Marks <=1500 AND i.Total_Marks >=990 THEN
INSERT INTO Result (STUD_NAME,CLASS) VALUES
(i.Stud_Name,'Distinction');
ELSIF i.Total_Marks <=989 AND i.Total_Marks >=900 THEN
INSERT INTO Result (STUD_NAME,CLASS) VALUES (i.Stud_Name,'First
Class');
ELSIF i.Total_Marks <=825 AND i.Total_Marks >=899 THEN
INSERT INTO Result (STUD_NAME,CLASS) VALUES (i.Stud_Name,'Higher
Second Class');
END IF;
END LOOP;
COMMIT;
END;
Course Outcome:
C306.4 Implement PL/SQL Code block for given requirements
Conclusion:
Students are able to PL/SQL Stored Procedure and Stored Function
Experiment No. 7
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 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.
Objective:
Implement PL/SQL Code block for given requirements
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:
The DECLARE Statement
Using the DECLARE statement you can declare a cursor and associate It with the SELECT statement
which fetches the desired records from a table. This SELECT statement associated with a cursor does
not allow INTO clause.
Once you declare a cursor you can retrieve records from it using the FETCH statement. You need to
make sure the cursor declaration precedes handler declarations. You can create use cursors in a single
stored program.
Syntax
Following is the syntax of the MySQL Cursor DECLARE Statement −
DECLARE cursor_name CURSOR FOR select_statement;
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:
OR
FETCH cursor_name INTO variable_list;
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
Cursor Syntax
The syntax for the CURSOR FOR LOOP in Oracle/PLSQL is:
FOR record_index in cursor_name LOOP
{...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,
Cursor display employee information from emp_information table whose emp_no four (4). DECLARE
cursor c(no number) is select * from emp_information where emp_no = no;
tmp emp_information%rowtype; BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no); dbms_output.put_line('EMP_Name:
'||tmp.emp_name); END Loop;
CLOSE c; END;
/
SQL>@parameter_cursor_demo
EMP_No: 4
EMP_Name: Zenia
Program
create database assi7;
use assi7;
show tables;
create table old_roll(roll int,name varchar(10));
create table new_roll(roll int,name varchar(10));
insert into old_roll values(4,'d');
insert into old_roll values(3,'bcd');
insert into old_roll values(1,'bc');
insert into old_roll values(5,'bch');
insert into new_roll values(2,'b');
insert into new_roll values(5,'bch');
insert into new_roll values(1,'bc');
loop2:loop
fetch c2 into newrollnumber,newname;
if done then
insert into new_roll values(oldrollnumber,oldname);
set done=false;
close c2;
leave loop2;
end if;
if oldrollnumber=newrollnumber then
leave loop2;
end if;
end loop;
end loop;
close c1;
end $
delimiter ;
call roll_list();
select * from new_roll;
Outcome:
C306.4 Implement PL/SQL Code block for given requirements
Conclusion: We have implemented all types of Cursors successfully.
Activity to be Submitted by Students
Write PL/SQL code to display Employee details using Explicit Cursors
Write PL/SQL code in Cursor to display employee names and salary.
Experiment: 08
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.
Objective: Study of All Types: Row level and Statement level triggers, beforeand After
Triggers
Theory:
What is a Trigger?
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete,
Update is executed on a database table. A trigger is triggered automatically when an associated
DML statement isexecuted.
Syntax of Triggers
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with
the given name or overwrites an existing trigger with the same name.
{BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the
trigger get fired. i.e for example: before or after updating a table. INSTEAD OF is used
to create a trigger ona view. before and after cannot be used to create a trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering
event. More than one triggering events can be used together separated by OR keyword.
The trigger gets fired at all the specified triggering event.
[OF col_name] - This clause is used with update triggers. This clause is used when you
want totrigger an event only when a specific column is updated.
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with
the givenname or overwrites an existing trigger with the same name.
[ON table_name] - This clause identifies the name of the table or view to which the
trigger is associated.
[REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and
new values of the data being changed. By default, you reference the values as
:old.column_name or
:new.column_name. The reference names can also be changed from old (or new) to any
other user-defined name. You cannot reference old values when inserting a record, or
new values whendeleting a record, because they do not exist.
[FOR EACH ROW] - This clause is used to determine whether a trigger must fire when
each row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql
statement is executed(i.e.statement level Trigger).
WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired
only for rows that satisfy the condition specified.
For Example: The price of a product changes constantly. It is important to maintain the history of
the prices of the products.
We can create a trigger to update the 'product_price_history' table when the price of the product
is updated in the 'product' table.
1) Create the 'product' table and 'product_price_history'
table CREATE TABLE product_price_history
(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
Once the above update query is executed, the trigger fires and updates the 'product_price_history' table.
4)If you ROLLBACK the transaction before committing to the database, the data inserted to
the table is also rolled back.
There are two types of triggers based on the which level it is triggered.
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement executed.
For Example: Let's create a table 'product_check' which we can use to store messages when
triggers are fired.
1) BEFORE UPDATE, Statement Level: This trigger will insert a record into the table
'product_check' before a sql update statement is executed, at the statement level.
2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table
'product_check' beforeeach row is updated.
3) AFTER UPDATE, Statement Level: This trigger will insert a record into the table
'product_check'after a sql update statement is executed, at the statement level.
4) AFTER UPDATE, Row Level: This trigger will insert a record into the table
'product_check' after each row is updated.
Lets check the data in 'product_check' table to see the order in which the trigger
is fired.SELECT * FROM product_check;
Output:
Mesage Current_Date
Before update, statement level 26-Nov-
2008 Before update, row level 26-Nov-
2008
After update, Row level 26-Nov-2008
The above result shows 'before update' and 'after update' row level events have occured twice, since
two records were updated. But 'before update' and 'after update' statement level events are fired
only once per sql statement.
Program:
Table created.
END; 5
/
Trigger created.
END; 5
/
Trigger created.
Table created.
1 row created.
Trigger dropped.
END; 5
/
Trigger created.
SQL> DELETE FROM LIBRARY WHERE BOOK_STATUS_ID=22;
1 row deleted.
SQL> SELECT * FROM
LIBRARY_AUDIT_STMT_LVL; STMT_TYPE
UPDATE_TS
AFTER DELETE
31-AUG-17 05.13.44.843418 PM
END; 4
/
Trigger created.
UPDATE_TS
AFTER DELETE
31-AUG-17 05.13.44.843418 PM
AFTER DELETE
31-AUG-17 05.20.54.175978 PM
BEFORE DELETE
31-AUG-17 05.24.25.852613 PM
STMT_TYPE
UPDATE_TS
AFTER DELETE
31-AUG-17 05.24.25.852880 PM
SQL> CREATE OR REPLACE TRIGGER TRIGGER_STMT_LVL_BEFORE_DELETE
BEFORE DELETE ON LIBRARY_AUDIT_STMT_LVL
2 BEGIN
3 INSERT INTO LIBRARY_AUDIT_STMT_LVL (STMT_TYPE, UPDATE_TS)
VALUES ('BEFORE DELETE'SQL> , CURRENT_TIMESTAMP);
4
END; 5
/
Trigger created.
END; 5
/
Trigger created.
Table created.
SQL> INSERT INTO LIBRARY VALUESQL> S(11,'DBMS');
1 row created.
1 row created.
SQL> SELECT * FROM LIBRARY;
BOOK_STATUS_ID BOOKNAME
11 DBMS
22 JAVA
Trigger dropped.
END; 5
/
Trigger created. 6 7 8 9 10 11 12 13
1 row deleted.
SQL> SELECT * FROM
LIBRARY_AUDIT_STMT_LVL; STMT_TYPE
UPDATE_TS
AFTER DELET 14 E
31-AUG-17 05.13.44.843418 PM
SQL> DROP TRIGGER TRIGGER_STMT_LVL_BEFORE_DELETE;
Trigger dropped.
SQL> DELETE 15 FROM LIBRARY WHERE BOOK_STATUS_ID 16 = 17 1 18 1;
1 row deleted.
SQL> SELECT * FROM
LIBRARY_AUDIT_STMT_LVL; STMT_TYPE
UPDATE_TS 19
20
AFTER DELETE
31-AUG-17 05.13.44.843418 PM
21
AFTER DEL 22 ETE
31- 23 AUG-17 05.20.54.175978 PM
1 row created.
Trigger created.
1 row deleted.
SQL> SE 32 LECT * FRO 33 M LIBRA 34
RY_AUDIT_STMT_LVL; STMT_TYPE
UPDATE_TS
35
AFTER DELETE
31-AUG-17 05.13.44.843418 PM
AFTER DELETE
31-AUG 36 -17 05.20.54.1759 37 78 PM
BEFORE DELETE
31-AUG-17 05.24.25.8 38 5 39 2 40 613 PM
STMT_TYPE
UPDATE_TS
41 42
AFTER DELETE
31-AUG-17 05.24.25.852880 PM
Conclusion: Thus have successfully studied and implemented All Types: Row level and
Statement level triggers, before and After Triggers
OUTCOMES:
Students will be able to create and test DML trigger.
Students will be able to identify the need and when to use triggers.
Experiment: 9
Title : Database Connectivity
Aim: Implement MYSQL/Oracle database connectivity with PHP/ python/Java Implement Database
navigation operations (add, delete, edit,) using ODBC/JDBC.
Objective: Java Database Connectivity with MySQL
In Java, we can connect our Java application with the MySQL database through the Java code. JDBC (
Java Database Connectivity) is one of the standard APIs for database connectivity, using it we can
easily run our query, statement, and also fetch data from the database.
Prerequisite to understand Java Database Connectivity with MySQL
1.You should have MySQL on your System.
2. You should have JDK on your System.
3. To set up the connectivity, the user should have MySQL Connector to the Java (JAR file),
the 'JAR' file must be in class path while compiling and running the code of JDBC.
Steps to download MySQL Connector
Step 1 – Search for MySQL community downloads.
Step 2 – Go to the Connector/J.
Step 3 – Select the Operating System platform-independent.
Step 4 – Download the zip file Platform Independent (Architecture Independent), ZIP Archive.
Step 5 – Extract the zip file.
Step 6 – Get the mysql-connector-java-8.0.20.jar file from the folder.
Setting up Database Connectivity with MySQL using JDBC code
Users have to follow the following steps:
Step 1 – Users have to create a database in MySQL (for example let the name of the database be
‘mydb’ ).
Step 2 – Create a table in that database.
Example:
create table designation
(
code int primary key auto_increment,
title char(35) not null unique
);
This is MySQL code for creating a table.
Step 3 – Now, we want to access the data of this table using Java database connectivity.
Create a directory in your main drive (named gfg).
Now, inside gfg created two more directories one named as ‘src‘ and the other ‘lib‘.
Put the MySQL connector java jar file in the lib folder.
Step 4 – We will write connectivity code in the src folder, To write connectivity code user must know
the following information:
Driver class:- The driver class for connectivity of MySQL database “com.mysql.cj.jdbc.Driver”,
after the driver has been registered, we can obtain a Connection instance that is connected to a
particular database by calling DriverManager.getConnection():, in this method, we need to pass
URL for connection and name and password of the database.
URL for Connection:- The connection URL for the mysql database is
jdbc:mysql://localhost:3306/mydb (‘mydb’ is the name of database).
Specify to the DriverManager which JDBC drivers to try to make Connections use below line:
Class.forName("com.mysql.cj.jdbc.Driver");
//Java program to set up connection and get all data from table
import java.sql.*;
// mydb is database
// mydbuser is name of database
// mydbuser is password of database
Statement statement;
statement = connection.createStatement();
ResultSet resultSet;
resultSet = statement.executeQuery(
"select * from designation");
int code;
String title;
while (resultSet.next()) {
code = resultSet.getInt("code");
title = resultSet.getString("title").trim();
System.out.println("Code : " + code
+ " Title : " + title);
}
resultSet.close();
statement.close();
connection.close();
}
catch (Exception exception) {
System.out.println(exception);
}
} // function ends
} // class ends
Output of ‘check.java‘ file in the src folder:
Title: Design and Develop MongoDB Queries using CRUD operations. (Use CRUD operations,
SAVE method, logical operators)
Theory:
MongoDB Save() Method
he db.collection.save() method is used to updates an existing document or inserts a new
document,depending on its document parameter.
Syntax
The basic syntax of MongoDB save() method is shown below −
Example
Following example will replace the document with the _id '5983548781331adf45ec7'.
>db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec7), "title":"Test1",
"by":"JIT"
}
save()method performs an insert since the document passed to the method does not contain
)
the_idfield. During the insert, the shell will create the _id field with a unique ObjectId
>db.mycol.find()
value, asverified by the inserted document.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New Topic",
save()performs an update withupsert:true since the document contains an_idfield.
"by":"DBMSTutor"}
{ "_id" :e.g. db.invoice.save( { _id: 1001,inv_no:
ObjectId(5983548781331adf45ec6), "I00001",
"title":"NoSQL inv_date: "10/10/2012", ord_qty:200 } );
Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Test1",”by” : ”JIT”}
>
Logical Oerators in MongoDB:
Name Description
$and Joins query clauses with a logical AND returns all documents that match the
conditions ofboth clauses.
$not Inverts the effect of a query expression and returns documents that do not match the
queryexpression.
$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
ofeither clause
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
e.g.
This query will select all documents in the inventory collection where:
db.inventory.find( {
$and : [
})
Experiment No 11
OBJECTIVES:
To create and manage different types of indexes in MongoDB for query execution
To learn the indexing and aggregation framework in MongoDB
2. MongoDB Server
THEORY:
AGGREGATION
Aggregations operations process data records and return computed results. Aggregation operations
group values from multiple documents together, and can perform a variety of operations on the grouped
data to return a single result. In sql count (*) and with group by is an equivalent of MongoDB
aggregation.
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
$group (aggregation)
$group :- Groups documents by some specified expression and outputs to the next stage a document
for each distinct grouping. The output documents contain a _id field which contains the distinct group by
key. The output documents can also contain computed fields that hold the values of some accumulator
expression grouped by the $group‘s _id field.
Aggregate Expressions:
Example
db.AggreExample.aggregate([{$group:{”_id”:”$State”,totalpop:{$sum:”$pop”}}}])
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
db.AggreExample.aggregate([{$group:{”_id”:”$State”,avgPop:{$avg:”$pop”}}}])
$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 documents to look at by the given number starting from the current
positions
Example:
db.AggreExample.aggregate( [
])
INDEXING
Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every
document of a collection to select those documents that match the query statement. This scan is highly
inefficient and require the 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 index.
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
To create an index, use ensureIndex() or a similar method from your driver. The ensureIndex() method
only creates an index if an index of the same specification does not already exist.
For example, the following operation creates an index on the userid field of the records collection:
db.records.ensureIndex({userid:1})
The value of the field in the index specification describes the kind of index for that field. For example, a
value of 1 specifies an index that orders items in ascending order. A value of -1 specifies an index that
orders items in descending order.
The created index will support queries that select on the field userid, such as the following:
MongoDB allows you to specify a unique constraint on an index. These constraints prevent applications
from inserting documents that have duplicate values for the inserted fields. MongoDB cannot create
a unique index on the specified index field(s) if the collection already contains data that would violate
the unique constraint for the index.
ensureIndex() method also accepts list of options (which are optional), whose list is given below:
Builds the index in the background so that building an index does not
background Boolean block other database activities. Specify true to build in the
background. The default value is false.
Creates a unique index so that the collection will not accept insertion
of documents where the index key or keys match an existing value in
unique Boolean
the index. Specify true to create a unique index. The default value is
false.
dropDups Boolean Creates a unique index on a field that may have duplicates. MongoDB
indexes only the first occurrence of a key and removes all documents
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
If true, the index only references documents with the specified field.
sparse Boolean These indexes use less space but behave differently in some
situations (particularly sorts). The default value is false.
index The index version number. The default index version depends on the
v
version version of MongoDB running when creating the index.
For a text index, the language that determines the list of stop words
default_language string and the rules for the stemmer and tokenizer. The default value is
english.
For a text index, specify the name of the field in the document that
language_override string contains, the language to override the default language. The default
value is language.
You can also enforce a unique constraint on compound indexes, as in the following prototype:
Sparse indexes
If a document does not have a value for a field, the index entry for that item will be null in any index that
includes it. Thus, in many situations you will want to combine the unique constraint with the sparse
option. Sparse indexes skip over any document that is missing the indexed field, rather than storing null
for the index entry. Since unique indexes cannot have duplicate values for a field, without the sparse
option, MongoDB will reject the second document and all subsequent documents without the indexed
field.
Hashed indexes compute a hash of the value of a field in a collection and index the hashed value.
These indexes permit equality queries and may be suitable shard keys for some collections. To create
a hashed index, specify hashed as the value of the index key, as in the following example:
db.orders.dropIndex(
{"cust_id":1,"ord_date":-1,"items":1}
The method returns a document with the status of the operation. Upon successful operation, the ok
field in the returned document should specify a 1.
OUTCOMES:
Experiment No 12
OBJECTIVES:
THEORY:
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
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
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 functionfunction(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 pairswhich is then reduced based on the keys that have multiple values. MapReduce
Command:
syntax of the basic mapReduce command:
db.collection.mapReduce(function(){emit(key,value);},//map function function(key,values)
{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 thathave multiple values.
map is a javascript function that maps a value with a key and emits a key-value pair
reduce is a javascript function that reduces or groups all the documents having the same key
out specifies the location of the map-reduce query result
query specifies the optional selection criteria for selecting documents
sort specifies the optional sort criteria
limit specifies the optional maximum number of documents to be returned
Map Reduce Example
The below example is to retrieve the sum of total values related to particular key.
1. Insert data in mapCollection.
db.mapc.insert({key:”a”, value:2})
db.mapc.insert({key:”a”, value:4})
CONCLUSION: Thus we studied how to Implement Map reduces operation with suitable
example using MongoDB.
OUTCOMES:
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
Students will be able to write queries for given requirements using Mongodb
Experiment No: 12
Title: Database Connectivity
Write a program to implement MongoDB database connectivity with any front end language to
implement Database navigation operations (add, delete, edit etc.)
OBJECTIVES:
IMPLEMENTATION:
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Updates;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.FindIterable;
import org.bson.Document;
import com.mongodb.MongoClient;
import java.util.Scanner;
import java.util.Iterator;
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n1. Insert Document \n2. Delete Document \n3. Update
Document \n4. Display All \n5. Display marks>75 \n6. Exit \nEnter your choice :");
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
choice = sc.nextInt();
switch (choice) {
case 1:insert(collection);
break;
case 2: deletedoc(collection);
break;
case 3: updatedoc(collection);
break;
case 4: displayAll(collection);
break;
case 5:display(collection);
break;
case 6: System.out.println("Exiting Program");
System.exit(0);
break;
default:
System.out.println(choice + " is not a valid Menu Option! Please Select
Another.");
}
}while(choice != 6 /*Exit loop when choice is 6*/);
}
catch(Exception ex){
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
ex.printStackTrace();
}
}
public static void insert(MongoCollection<Document> collection) {
System.out.println("Inserting document");
Document document = new Document();
Scanner sc=new Scanner(System.in);
System.out.println("Enter roll no:");
int rollno = sc.nextInt();
System.out.println("Enter name:");
String name= sc.next();
System.out.println("Enter class:");
String classs=sc.next();
System.out.println("Enter marks:");
int marks= sc.nextInt();
System.out.println("Enter technical interests:");
String techint=sc.next();
document.append("roll_no",rollno);
document.append("name",name);
document.append("class",classs);
document.append("marks",marks);
document.append("technical_interests",techint);
collection.insertOne(document);
Subject Code: 310246 Subject Name: Database Management Systems Laboratory
SEM-I
System.out.println(it.next());
i++;
}
}
}
1.Display all records from Collection Students.
OUTCOMES: