DBMS Student Manual R2021 - 240304 - 200546
DBMS Student Manual R2021 - 240304 - 200546
STUDENT MANUAL
Semester IV
Regulation 2021
i
TABLE OF CONTENTS
Page
S. No. Particulars
No.
1 College Vision and Mission statement 3
2 Department Vision, Mission, PEOs, POs and PSOs 4
3 Syllabus 7
4 List of Experiments Mapping with COs, POs &PSOs 9
5 University prescribed lab experiments
1 .DATA DEFINITION IN SQL (DDL)
11
2. DATA MANIPULATION IN SQL(DML) 14
3. DATA CONTROL IN SQL (DCL) 16
4.CONSTRAINTS 20
5.JOINS 25
6.VIEWS 27
7.NESTED QUERIES 29
8.AGGREGATE FUNCTIONS 31
9.SET OPERATIONS 35
10.CURSORS 36
11.PROCEDURES 38
12.FUNCTIONS 40
13.CONTROL STRUCTURES 42
14.TRIGGERS 47
15.XML DATABASE 50
16.DOCUMENT BASED DATAUSING NOSQL 52
DATABASE TOOLS
17.BANKING SYSTEM 54
ii
INSTITUTE -VISION AND MISSION
Vision
To develop students with intellectual curiosity and technical expertise to meet the global needs.
Mission
M1: To achieve academic excellence by offering quality technical education using best teaching
techniques.
M3 : To develop interpersonal skills along with value based education in a dynamic learning
environment.
iii
Department of Computer Science and Engineering
Department Vision:
To produce globally competent technical professionals for digitized society.
Department Mission:
: To establish conducive academic environment by imparting quality education and
value added training.
: To encourage students to develop innovative projects to optimally resolve the
challenging social problems.
1
Program Outcomes (POs) for Computer Science and Engineerin
2
PO9 Individual and Function effectively as an individual, and as a member or leader in
team work diverse teams, and in multidisciplinary settings.
PO10 Communication Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able
to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive
clear instructions.
PO11 Project Demonstrate knowledge and understanding of the engineering and
management management principles and apply these to one’s own work, as a
and finance member and leader in a team, to manage projects and in
multidisciplinary environments.
PO12 Life-long Recognize the need for, and have the preparation and ability to
learning engage in independent and life-long learning in the broadest context
of technological change.
PSO1 Deal with real time problems by understanding the evolutionary changes in computing,
applying standard practices and strategies in software project development using open-
ended programming environments.
PSO2 Employ modern computer languages , environments and platforms in creating innovative
career paths by inculcating moral values and ethics.
PSO3 Achieve additional expertise through add-on and certificate programs.
3
CS3481 DATABASE MANAGEMENT SYSTEMS LABORATORY LTPC
0 0 3 1.5
OBJECTIVES:
LIST OF EXPERIMENTS:
1. Create a database table, add constraints (primary key, unique, check, Not null), insert rows, update and
delete rows using SQL DDL and DML commands.
2. Create a set of tables, add foreign key constraints and incorporate referential integrity.
3. Query the database tables using different ‘where’ clause conditions and also implement aggregate functions.
4. Query the database tables and explore sub queries and simple join operations.
5. Query the database tables and explore natural, equi and outer joins.
6. Write user defined functions and stored procedures in SQL.
7. Execute complex transactions and realize DCL and TCL commands.
8. Write SQL Triggers for insert, delete, and update operations in a database table.
9. Create View and index for database tables with a large number of records.
10. Create an XML database and validate it using XML schema.
11. Create Document, column and graph-based data using NOSQL database tools.
12. Develop a simple GUI based database application and incorporate all the above-mentioned features
13. Case Study using any of the real-life database applications from the following list
a) Inventory Management for a EMart Grocery Shop
b) Society Financial Management
c) Cop Friendly App – Eseva
d) Property Management – eMall
e) Star Small and Medium Banking and Finance
● Build Entity Model diagram. The diagram should align with the business and
functional goals stated in the application
● Apply Normalization rules in designing the tables in scope.
● Prepared applicable views, triggers (for auditing purposes), functions for
enabling enterprise grade features.
● Build PL SQL / Stored Procedures for Complex Functionalities, ex EOD Batch
Processing for calculating the EMI for Gold Loan for each eligible Customer.
● Ability to showcase ACID Properties with sample queries with appropriate
settings
4
TOTAL: 45 PERIODS
OUTCOMES:
5
CS3481 DATABASE MANAGEMENT SYSTEMS LABORATORY
Course Outcomes
After completion of the course, Students are able to learn the listed Course Outcomes.
Knowledge
Cos Course Code Course Outcomes
Level
Create databases with different types of key constraints. K4
CO1 C217.1
Construct simple and complex SQL queries using DML
K3
CO2 C217.2 and DCL commands.
Use advanced features such as stored procedures and
K3
triggers and incorporate in GUI based application
CO3 C217.3
development
Create an XML database and validate with meta-data (XML K3
CO4 C217.4 schema). .
Exp.No.
Name of the Experiment COs POs PSOs
6
8. AGGREGATE FUNCTIONS CO1,2 PO1,2,3 PSO1,2
7
Program Outcomes
8
SQL – AN INTRODUCTION
What is Database?
A database is a separate application that stores a collection of data. Each database has one or more
distinct application programming interfaces (API) for creating, accessing, managing, searching and
replicating the data it holds.
Other kinds of data stores can be used, such as files on the file system or large hash tables in
memory but data fetching and writing would not be so fast and easy with those types of systems.
So nowadays, we use relational database management systems (RDBMS) to store and manage huge
volume of data. This is called relational database because all the data is stored into different tables and
relations are established using primary keys or other keys known as foreign keys.
RDBMS Terminology:
Before we proceed to explain SQL database system, let's revise few definitions related to database.
9
A table is uniquely identified by its name and consists of rows that contain the stored information,
each row containing exactly one tuple (or record). A table can have one or more columns.
A column is made up of a column name and a data type, and it describes an attribute of the tuples.
The structure of a table, also called relation schema, thus is defined by its attributes.The type of information
to be stored in a table is defined by the data types of the attributes at table creation time.
SQL uses the terms table, row, and column for relation, tuple, and attribute, respectively.
• char(n): Fixed-length character data (string), n characters long. The maximum size for n is 255 bytes (2000
in Oracle8). Note that a string of type char is always padded on right with blanks to full length of n. (+ can
be memory consuming).
Example: char(40)
• varchar2(n): Variable-length character string. The maximum size for n is 2000 (4000 in Oracle8). Only
the bytes used for a string require storage.
Example: varchar2(80)
• number(o, d): Numeric data type for integers and reals. o = overall number of digits, d = number of digits
to the right of the decimal point.
Maximum values: o =38, d= −84 to +127. Examples: number(8), number(5,2)
• DateDate data type for storing Date and time.
The default format for a Date is: ‘YYYY-MM-DD’. Examples: ’1997-10-10’;
• Long: Character data up to a length of 2GB. Only one long column is allowed per table.
• the order in which tuples appear in a table is not relevant (unless a query requires an
explicit sorting).
• a table has no duplicate tuples (depending on the query, however, duplicate tuples can
appear in the query result).
A database schema is a set of relation schemas. The extension of a database schema at database run-
time is called a database instance or database.
10
EX.NO:1 DATA DEFINITION IN SQL (DDL)
AIM:
To implement data definition commands using SQL.
DESCRIPTION:
Creating Tables
TheSQL command for creating an empty table has the following form:
For each column, a name and a data type must be specified and the column name must be unique within the
table definition. Column definitions are separated by comma. There is no difference between names in lower
case letters and names in upper case letters. In fact, the only place where upper and lower case letters matter
are strings comparisons.
A not null constraint is directly specified after the data type of the column and the constraint requires
defined attribute values for that column, different from null.
Unless the condition not null is also specified for this column, the attribute value null is allowed and two
tuples having the attribute value null for this column do not violate the constraint.
The keyword unique specifies that no two tuples can have the same attribute value for this column.
Checklist for Creating Tables
The following provides a small checklist for the issues that need to be considered before creating a table.
• What are the attributes of the tuples to be stored? What are the data types of the attributes? Should
varchar2 be used instead of char?
• Which columns build the primary key?
• Which columns do (not) allow null values? Which columns do (not) allow duplicates?
• Are there default values for certain columns that allow null values?
It is possible to modify the structure of a table (the relation schema) even if rows have already been inserted
into this table.
A column can be added using the alter table command
If more than only one column should be added at one time, respective add clauses need to be
separated by colons. A table constraint can be added to a table using
Note:
A column constraint is a table constraint, too. not null and primary key constraints can only be added to a
table if none of the specified columns contains a null value. Table definitions can be modified in an
analogous way. This is useful, e.g., when the size of strings that can be stored needs to be increased. The
syntax of the command for modifying a column is
11
alter table <table>
modify(<column> [<data type>] [default <value>] [<column constraint>]);
Note:
In earlier versions of Oracle it is not possible to delete single columns from a table definition. A workaround
is to create a temporary table and to copy respective columns and rows into this new table.
Renaming a Table
Deleting a Table
OUTPUT:
l.Creating Tables
SQL> create table student(sno number(9), stu_name varchar(9) not null, rollno number(9) not null
dob date, phone_no number(10) );
Table description
MODIFY:
Table description
Renaming a Table
12
Table description
Table description:
RESULT:
Thus the data definition commands have been used to create , alter , and drop table using SQL
queries.
13
EX NO:2 DATA MANIPULATION IN SQL(DML)
AIM:
To implement data manipulation using SQL queries.
DESCRIPTION:
After a table has been created using the create table command, tuples can be inserted into the table, or tuples
can be deleted or modified.
Insertions
The most simple way to insert a tuple into a table is to use the insert statement
For each of the listed columns, a corresponding (matching) value must be specified. Thus an insertion does
not necessarily have to follow the order of the attributes as specified in the create table statement. If a
column is omitted, the value null is inserted instead. If no column list is given, however, for each column as
defined in the create table statement a value must be given.
If there are already some data in other tables, these data can be used for insertions into a new table. For this,
we write a query whose result is a set of tuples to be inserted. Such an insert statement has the form
UpDates
For modifying attribute values of (some) tuples in a table, we use the upDate statement:
upDate<table> set
<column i> = <expression i>, . . . , <column j> = <expression j>
[where <condition>];
Note: that the new value to assign to <column i> must a matching data type.
An upDate statement without a where clause results in changing respective attributes of all
tuples in the specified table. Typically, however, only a (small) portion of the table requires an upDate.
Deletions
All or selected tuples can be deleted from a table using the delete command:
If the where clause is omitted, all tuples are deleted from the table. An alternative command for deleting all
tuples from a table is the truncate table <table> command. However, in this case, the deletions cannot be
undone.
OUTPUT:
SQL> create table EMP (EMPNO number(4) not null, ENAME varchar2(30) not null,
JOB varchar2(10), MGR number(4), HIREDATE Date, SAL number(7,2), DEPTNO number(2));
14
INSERT
Type 1
SQL> insert into emp (empno,ename,job,mgr,hireDate,sal,deptno)values (3737,'Priya','Analyst','7777','07-
mar-2022',34000,07);
Type 2
TUPLE DELETION
RESULT:
Thus data manipulation language queries have been implemented and verified using SQL.
15
EX.NO:3 DATA CONTROL IN SQL (DCL)
AIM:
To implement data control language using SQL.
DESCRIPTION:
Selections
Selecting Columns
The columns to be selected from a table are specified after the keyword select. This operation
is also called projection.
The query
lists only the attribute values of specified columns for each tuple from the denoted relation.
If all columns should be selected, the asterisk symbol “*“can be used to denote all attributes.
The query
Instead of an attribute name, the select clause may also contain arithmetic expressions involving arithmetic
operators etc.
The query
retrieves all tuples with column specified as a product with the specified number from the table.
For the different data types supported in Oracle, several operators and functions are provided:
• for numbers: abs, cos, sin, exp, log, power, mod, sqrt, +,−, _, /, . . .
• for strings: chr, concat(string1, string2), lower, upper, replace(string, search string,
replacement string), translate, substr(string, m, n), length, to Date, . . .
• for the Date data type: add month, month between, next day, to char, . . .
Inserting the keyword distinct after the keyword select, duplicate result tuples are automatically eliminated.
Order by
It is also possible to specify a sorting order in which the result tuples of a query are displayed. For this the
order by clause is used and which has one or more attributes listed in the select clause as parameter,
descspecifies a descending order and asc specifies an ascending order (this is also the default order).
The query
16
displays the result in an ascending order by the attribute <column i>. If two tuples have the same attribute
value, the sorting criteria is a descending order by the attribute values of
<column j>.
Selection of Tuples
Where
To conditionally select the datas from a table, we use the where keyword.
And Or
the where keyword can be used to conditionally select data from a table. This condition can be a simple
condition (like the one presented in the previous section), or it can be a compound condition. Compound
conditions are made up of multiple simple conditions connected by AND or OR. There is no limit to the
number of simple conditions that can be present in a single SQL statement.
Select "column_name"
From "table_name"
Where "simple condition"
{[AND|OR] "simple condition"}+
The {}+ means that the expression inside the bracket will occur one or more times. Note that AND and OR
can be used interchangeably. In addition, we may use the parenthesis sign () to indicate the order of the
condition.
In
The IN keyword, when used with where in this context, we know exactly the value of the returned values we
want to see for at least one of the columns. The syntax for using the IN keyword is as follows:
The number of values in the parenthesis can be one or more, with each values separated by comma. Values
can be numerical or characters. If there is only one value inside the parenthesis, this commend is equivalent
to
Also
17
Between
Whereas the IN keyword help people to limit the selection criteria to one or more discrete values, the
BETWEEN keyword allows for selecting a range.
This will select all rows whose column has a value between 'value1' and 'value2'.
For all data types, the comparison operators =, != or <>,<, >,<=, => are allowed in the conditions of a where
clause.
For a tuple to be selected there must (not) exist a defined value for this column.
value: <column> is [not] null
OUTPUT:
SELECT
DISTINCT
SQL> select distinct mgr from emp;
ORDER BY
18
IN
SQL> select ename,sal from emp where empno in (2323,5555);
SQL> select ename,salfrom emp where empno in (2323,7575);
BETWEEN
SQL> select ename,sal from emp where sal between 25000 and 50000;
RESULT:
Thus data query languages have been implemented and verified using SQL.
19
EX.NO:4 CONSTRAINTS
AIM:
To implement various types of constrains using SQL.
DESCRIPTION:
Constraints are used to limit the type of data that can go into a table. Such constraints can be specified when
the table is first created via the CREATE TABLE statement, or after the table is already created via the
ALTER TABLE statement.
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
CHECK Constraint: Makes sure that all values in a column satisfy certain criteria.
PRIMARY KEY Constraint: Used to uniquely identify a row in the table.
FOREIGN KEY Constraint: Used to ensure referential integrity of the data.
By default, a column can hold NULL. If you not want to allow NULL value in a column, you will want to
place a constraint on this column specifying that NULL is now not an allowable value.
DEFAULT Constraint
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not
provide a specific value.
The syntax used is
UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are distinct.
20
CHECK Constraint
The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the
database will only insert a new row or upDate an existing row if the new value satisfies the CHECK
constraint. The CHECK constraint is used to ensure data quality.
A primary key is used to uniquely identify each row in a table. It can either be part of the actual record itself,
or it can be an artificial field (one that has nothing to do with the actual record). A primary key can consist of
one or more fields on a table. When multiple fields are used as a primary key, they are called a composite
key.
Primary keys can be specified either when the table is created (using CREATE TABLE) or by changing the
existing table structure (using ALTER TABLE).
Or
Create table <table> (
<column 1><data type>,
.........
<column n><data type>
);
Note: Before using the ALTER TABLE command to add a primary key, you'll need to make sure that the
field is defined as 'NOT NULL' -- in other words, NULL cannot be an accepted value for that field.
A foreign key is a field (or fields) that points to the primary key of another table. The purpose of the foreign
key is to ensure referential integrity of the data. In other words, only values that are supposed to appear in the
database are permitted.
21
<column m><data type> REFERENCES <table>
);
Or
OUTPUT:
CONSTRAINTS
UNIQUE
NOT NULL
CHECK
22
Last_Name varchar (30),
First_Name varchar(30));
SQL> insert into customer values ('244','ram ','pri');
SQL> insert into customer values ('23','uma','ram');
PRIMARY KEY
SQL> CREATE TABLE Customer (SID integer, Last_Name varchar(30), First_Name varchar(30),
PRIMARY KEY (SID));
SQL> desc customer
SQL> insert into customer values('34','ram','pri');
SQL> insert into customer values('54','oop','raj');
SQL> insert into customer values('54','tem','temp');
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C00602) violated
SQL> insert into customer values('','trim','trimi');
23
SQL> select * from customer;
ON DELETE CASCADE
RESULT:
Thus, various types of constrains have been implemented and verified using SQL.
24
EX.NO:5 JOINS
AIM:
To implement joins using SQL.
DESCRIPTION:
This is a binary operation that allows two relations to combine certain selections and cartesian
product into one resulting relation.
TYPES OF JOIN
- Inner join
- Outer join
INNER - JOIN
Here, join operation forms a cartesian product of two relation’s arguments, performs a selection
forcing equality on those attributes that appear in both relation schemes and finally removes
duplicate attributes. Also, this is referred as inner join.
The query
Select *
From <table1>,<table2>
Where table1.column i = table2.column i;
OUTER – JOIN
The outer-join operation is an extension of the join operation to deal with missing information.
This takes all tuples in the left relation that did not match with any tuple in the right relation, pads
the tuples with null values for all other attributes from the right relation and adds them to the result
of the join operation.
The query
Select *
From <table1>,<table2>
Where table1.column i(+) = table2.column i;
25
Select *
From <table1>,<table2>
Where table1.column i = table2.column i(+);
This pads tuples from the left relation that did not match any from the right relation, as well as
tuples from the right relation that did not match any from the left relation and adds them to the
resultant relation.
Note
OUTPUT:
JOINS
Table description
SQL> desc table1;
Table values
SQL> select * from table1;
SQL> select * from table1;
Table description
SQL>desc table2;
Table values
SQL> select *from table2;
INNER JOIN
SQL> select *from table1,table2 where table1.id=table2.id;
OUTER JOIN
LEFT OUTER JOIN
RESULT:
26
EX.NO:6 VIEWS
AIM:
To implement views using SQL.
DESCRIPTION:
A view is a virtual table. A view consists of rows and columns just like a table. The difference
between a view and a table is that views are definitions built on top of other tables (or views), and do not
hold data themselves. If data is changing in the underlying table, the same change is reflected in the view. A
view can be built on top of a single table or multiple tables. It can also be built on top of another view.
Views are allowed to use one of the following constructs in the view definition:
Joins
Aggregate function such as sum, min, max etc.
Set-valued subqueries (in, any, all) or test for existence (exists)
Group by clause or distinct clause
Views are classified as
Read – Only views
Updatable views
Updatable Views
These views are created from individual relation.
1. Ease of use: A view hides the complexity of the database tables from end users. Essentially we
can think of views as a layer of abstraction on top of the database tables.
2. Space savings: Views takes very little space to store, since they do not store actual data.
3. Additional data security: Views can include only certain columns in the table so that only the
non-sensitive columns are included and exposed to the end user. In addition, some databases allow
views to have different security settings, thus hiding sensitive data from prying eyes.
CREATE VIEW
The syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
DELETE VIEW
The syntax
27
Drop view <view-name>;
OUTPUT:
VIEW
CREATE VIEW
View created from more than one table leading to ‘Read Only’ view.
SQL> create view view1 as select emp.ename,empp.ph_no from emp,empp where
emp.empno=empp.empno;
SQL> select * from view1;
RESULT:
Thus views have been implemented and verified using SQL.
28
EX.NO:7 NESTED QUERIES
AIM:
To implement the nested query using SQL.
DESCRIPTION:
A query result can also be used in a condition of a where clause. In such a case the query is called a subquery
and the complete select statement is called a nested query.
A respective condition in the where clause then can have one of the following forms:
1. Set-valued subqueries
• For the clause any, the condition evaluates to true if there exists at least on row selected
by the subquery for which the comparison holds. If the subquery yields an empty result
set, the condition is not satisfied.
• For the clause all, in contrast, the condition evaluates to true if for all rows selected by
the subquery the comparison holds. In this case the condition evaluates to true if the
subquery does not yield any row or value.
For all and any, the following equivalences hold:
in , = any
not in , <> all or != all
Often a query result depends on whether certain rows do (not) exist in (other) tables. Such
type of queries is formulated using the exists operator.
OUTPUT:
NESTED QUERY (SUB QUERY)
Table Description
SQL> select * from EMP E1 where DEPTNO in (select DEPTNO from EMP E where E.DEPTNO =7);
SUBQUERY USING ANY
SQL> select * from EMP where SAL >= any (select SAL from EMP where DEPTNO =8);
SQL> select * from EMP where SAL >= any (select SAL from EMP where DEPTNO =8)
and DEPTNO = 7;
29
SUBQUERY USING ALL
SQL> select * from EMP where SAL > all (select SAL from EMP where DEPTNO = 7)
and DEPTNO <> 15;
SQL> select * from empp where exists (select * from EMP where emp.empno=empp.empno);
SQL> select * from empp where not exists (select * from EMP where emp.empno=empp.empno);
RESULT:
Thus, the nested queries using SQL has been implemented and verified.
30
EX.NO:8 AGGREGATE FUNCTIONS
AIM:
To implement various aggregate functions using SQL.
DESCRIPTION:
Aggregate functions are statistical functions such as count, min, max etc. They are used to compute a single
value from a set of attribute values of a column.
AVG Function
SUM Function
MIN Function
SQL uses the MIN function to find the maximum value in a column.
MAX Function
SQL uses the MAX function to find the maximum value in a column.
COUNT Function
Another arithmetic function is COUNT. This allows us to COUNT up the number of row in a certain table.
31
VARIANCE Function
SQL uses the VARIAVCE function to find the variance value of a column.
SQL uses the STDDEV function to find the standard deviation of a column.
GROUP BY Function
Often applications require grouping rows that have certain properties and then applying an aggregate
function on one column for each group separately. For this, SQL provides the clause group by <group
column(s)>. This clause appears after the where clause and must refer to columns of tables listed in the from
clause.
select <column(s)>
from <table(s)>
where <condition>
group by <group column(s)>;
HAVING CLAUSE
The HAVING clause, which is reserved for aggregate functions. The HAVING clause is typically placed
near the end of the SQL statement, and a SQL statement with the HAVING clause may or may not include
the GROUP BY clause.
select <column(s)>
from <table(s)>
where <condition>
group by <group column(s)>
[having <group condition(s)>];
OUTPUT:
AGGREGATE FUNCTIONS
SQL> desc emp;
SQL> select * from emp;
AVG
SQL> select avg(sal) from emp;
SUM
32
SQL> select sum(sal) total_salary from emp;
MIN
SQL> select min(ename) from emp;
MAX
SQL> select max(hireDate) from emp;
COUNT
SQL> select count(mgr) from emp;
VARIANCE
SQL> select job,sum(sal) from emp group by (job) having sum(sal) > 70000;
CHARACTER STRING
LENGTH
UPPER
SQL> select upper(ename) from emp;
LOWER
SQL> select lower(ename) from emp;
33
SUBSTR
SQL> select ename,substr(ename,3,3) from emp;
SQL> select ename,translate(ename,'a','e') from emp;
STRING OPERATION
These are special commands to work on strings.
SQL> select ename from emp;
SQL> select ename from emp where ename like 'pri%';
SQL> select ename from emp where ename like 'Pri%';
SQL> select ename from emp where ename like 'Pri %';
SQL> select ename from emp where ename like '%th';
SQL> select ename from emp where ename like '%th_';
SQL> select ename from emp where ename like ' th
SQL> select ename from emp where ename like ' th%';
SQL> select ename from emp where ename like ' r%';
SQL> select ename from emp where ename like '_a%';
SQL> select ename from emp where ename like '_a_th';
SQL> select ename from emp where ename like '_a_th%';
RESULT:
Thus the various aggregate functions using SQL has been implemented and verified.
34
EX.NO:9 SET OPERATIONS
AIM:
To implement set operations using SQL.
DESCRIPTION:
Sometimes it is useful to combine query results from two or more queries into a single result.
• union [all] returns a table consisting of all rows either appearing in the result of <query1> or in the result
of <query 2>.
Duplicates are automatically eliminated unless the clause all is used.
• intersect returns all rows that appear in both results <query 1> and <query 2>.
• minus returns those rows that appear in the result of <query 1> but not in the result of
<query 2>.
OUTPUT:
SET OPERATIONS
SQL> select rollno from tab1 union all select rollno from tab2;
NTERSECT
SQL> select rollno from tab1 intersect select rollno from tab2;
MINUS
SQL> select rollno from tab1 minus select rollno from tab2;
CARTESIAN PRODUCT
RESULT:
Thus, the set operations using SQL has been implemented and verified.
35
EX.NO:10 CURSORS
AIM:
To execute PL/SQL code using cursor.
DESCRIPTION:
A cursor is a SELECT statement that is defined within the declaration section of your PL/SQL code.
We'll take a look at three different syntaxes for cursors.
A cursor must be declared and opened before it can be used, and it must be closed to deactivate it after it is
no longer required. Once the cursor has been opened, the rows of the query result can be retrieved one at a
time using a FETCH statement.
DECLARE CURSOR
The DECLARE CURSOR statement defines the specific SELECT to be performed and associates a cursor
name with the query.
CURSOR cursor_name
IS
SELECT_statement;
OPEN CURSOR
The OPEN statement executes the query and identifies all the rows that satisfy the query search condition,
and positions the cursor before the first row of this result table.
Syntax
FETCH CURSOR
The FETCH statement retrieves the next row of the active set.Syntax
36
CLOSE CURSOR
The CLOSE statement is used to close the cursor that is currently open.
Syntax
OUTPUT:
CURSORS
RESULT:
Thus the cursors using PL/SQL has been implemented and verified.
37
EX.NO:11
PROCEDURES
AIM:
To execute PL/SQL program with procedure.
DESCRIPTION:
The syntax for a procedure is:
When you create a procedure or function, you may define parameters. There are three types of parameters
that can be declared:
1. IN - The parameter can be referenced by the procedure or function. The value of the parameter can
not be overwritten by the procedure or function.
2. OUT - The parameter can not be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.
3. IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.
The optional clause or replace re-creates the procedure. A procedure can be deleted using the command drop
procedure <procedure name>.
OUTPUT:
PROCEDURES
SQL> CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;6 /
SQL> set serverout on;
SQL> BEGIN
greetings;
END;4 /
SQL> DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number)IS
BEGIN
38
IF x < y THEN8
z:= x;
ELSE
z:=
y;END IF;
END;
BEGIN
a:=&a;
b:=&b;
findMin(a, b, c);
dbms_output.put_line(' Minimum of'||a||'and'||b||'is'||c);
end;
/
Enter value for a: 5
old 14: a:=&a;
new 14: a:=5;
Enter value for b: 2
old 15: b:=&b;
new 15: b:=2;
RESULT:
Thus, the procedure using PL/SQL has been implemented and verified.
39
EX.NO:12 FUNCTIONS
AIM:
To execute PL/SQL program with function.
DESCRIPTION:
The syntax for a function is:
When you create a procedure or function, you may define parameters. There are three types of
parameters that can be declared:
1. IN - The parameter can be referenced by the procedure or function. The value of the parameter can
not be overwritten by the procedure or function.
2. OUT - The parameter can not be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.
3. IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.
The optional clause or replace re-creates the function. A function can be deleted using the command drop
function <function name>.
OUTPUT:
FUNCTIONS
SQL> desc phonebook;
SQL> select * from phonebook;
SQL> create or replace function findAddress(phone in number) return varchar2 as address varchar2(100);
SQL>select username||','||doorno ||','||street ||','||place||','||pincode into address from phonebook where
phone_no=phone;
SQL>return address;
SQL> declare
address varchar2(100);
begin
address:=findaddress(25301);
dbms_output.put_line(address);
end;7 /
40
SQL> declare
address varchar2(100);
begin
address:=findaddress(25601);
dbms_output.put_line(address);
end;7 /
RESULT:
Thus the functions has been implemented and verified using PL/SQL.
41
EX.NO:13
CONTROL STRUCTURES
AIM:
To implement control structures using PL/SQL.
DESCRIPTION:
IF STATEMENTS
The structure of the PL/SQL IF statement is similar to the structure of IF statements in other procedural
languages. It allows PL/SQL to perform actions selectively based on conditions.
IF-THEN-END IF
Syntax:
IF condition THEN
Statements;
END IF;
IF-THEN-ELSE-END IF
Syntax:
IF condition THEN
Statement 1;
ELSE
Statement 2;
END IF;
IF-THEN-ELSIF-END IF
Syntax:
IF condition THEN
Statement 1;
[ELSIF condition THEN
Statement 2;]
……
[ELSIF
Statements n;]
END IF;
If the condition is FALSE or NULL, PL/SQL ignores the statements in the IF block. In either case, control
resumes at the next statement in the program following the END IF.
FOR LOOP
FOR loops have the general structure as the basic loop. In addition they have a control statement before the
LOOP keyword to determine the number of iterations that PL/SQL performs.
42
END LOOP;
COUNTER – An explicitly declared integer whose value automatically increases by 1 on each iteration of
the loop until the upper or lower bound is reached.
REVERSE – Causes the counter to decrement with each iteration from the upper bound to the lower bound.
LOWER_BOUND – The lower bound for the range of counter values.
UPPER_BOUND – The upper bound for the range of counter values.
WHILE LOOP
The WHILE loop is used to repeat a sequence of statements until the controlling condition is no longer true.
The condition is evaluated at the start of each iteration. The loop terminates when the condition is false. If
the condition is false at the start of the loop, then no futher iterations are performed.
The syntax for while loop is
OUTPUT:
CONTROL STRUCTURES
IF…..THEN…..ENDIF
43
8 dbms_output.put_line('Calculated value :: ' || b);
9 end if;
10 end;
11 /
Enter value for a: 45
old 5: a := &a;
new 5: a := 45;
Calculated value :: 5
SQL> /
Enter value for a: 23
old 5: a := &a;
new 5: a := 23;
IF…..THEN…..ELSE…..ENDIF
SQL> declare
2 a number;
3 b number;
4 begin
5 a := &a;
6 if a > 40 then
7 b := a - 40;
8 dbms_output.put_line('Calculated value :: ' || b);
9 else
10 dbms_output.put_line('No calculated value');
11 end if;
12 end;
13 /
Enter value for a: 67
old 5: a := &a;
new 5: a := 67;
Calculated value :: 27
SQL> /
Enter value for a: 34
old 5: a := &a;
new 5: a := 34;
No calculated value
ELSIF LADDER
SQL> set serveroutput on;
SQL> declare
2 a number;
3 b number;
4 c number;
5 d number;
6 begin
7 a:=&a;
8 b:=&b;
9 c:=&b;
44
10 if(a>b)and(a>c) then
11 dbms_output.put_line('A is maximum');
12 elsif(b>a)and(b>c)then
13 dbms_output.put_line('B is maximum');
14 else
15 dbms_output.put_line('C is maximum');
16 end if;
17 end;
18 /
FOR LOOP
SQL> declare
2 n number;
3 sum1 number default 0;
4 endvalue number;
5 begin
6 endvalue:=&endvalue;
7 n:=1;
8 for n in 1..endvalue
9 loop
10 if mod(n,2)=1
11 then
12 sum1:=sum1+n;
13 end if;
14 end loop;
15 dbms_output.put_line('sum ='||sum1);
16 end;
17 /
Enter value for endvalue: 5
old 6: endvalue:=&endvalue;
new 6: endvalue:=5;
sum =9
SQL> /
Enter value for endvalue: 56
old 6: endvalue:=&endvalue;
new 6: endvalue:=56;
sum =784
45
WHILE…..LOOP
RESULT:
Thus, the control structures has been implemented using PL/SQL.
46
EX.NO:14 TRIGGERS
AIM:
To implement PL/SQL program using triggers.
DESCRIPTION:
Complex integrity constraints that refer to several tables and attributes (as they are known as
assertions in the SQL standard) cannot be specified within table definitions.
Triggers, in contrast, provide a procedural technique to specify and maintain integrity constraints.
Triggers even allow users to specify more complex integrity constraints since a trigger essentially is a
PL/SQL procedure. Such a procedure is associated with a table and is automatically called by the database
system whenever a certain modification (event) occurs on that table. Modifications on a table may include
insert, update, and delete operations.
Structure of Triggers
A trigger definition consists of the following (optional) components:
• trigger name
create [or replace] trigger <trigger name>
• trigger time point
before | after
• triggering event(s)
insert or update [of <column(s)>] or delete on <table>
• trigger type (optional)
for each row
• trigger restriction (only for each row triggers !)
when (<condition>)
• trigger body
<PL/SQL block>
<trigger_body>
Some important points to note:
You can create only BEFORE and AFTER triggers for tables. (INSTEAD OF triggers are only
available for views; typically they are used to implement view upDates.)
You may specify up to three triggering events using the keyword OR. Furthermore, UPDATE can be
optionally followed by the keyword OF and a list of attribute(s) in <table_name>. If present, the OF
clause defines the event to be only an upDate of the attribute(s) listed after OF.
If FOR EACH ROW option is specified, the trigger is row-level; otherwise, the trigger is statement-
level.
47
Only for row-level triggers:
o The special variables NEW and OLD are available to refer to new and old tuples
respectively.
Note: In the trigger body, NEW and OLD must be preceded by a colon (":"), but in the
WHEN clause, they do not have a preceding colon! See example below.
o The REFERENCING clause can be used to assign aliases to the variables NEW and OLD.
o A trigger restriction can be specified in the WHEN clause, enclosed by parentheses. The
trigger restriction is a SQL condition that must be satisfied in order for Oracle to fire the
trigger. This condition cannot contain subqueries. Without the WHEN clause, the trigger is
fired for each row.
<trigger_body> is a PL/SQL block, rather than sequence of SQL statements. Oracle has placed
certain restrictions on what you can do in <trigger_body>, in order to avoid situations where one
trigger performs an action that triggers a second trigger, which then triggers a third, and so on, which
could potentially create an infinite loop. The restrictions on <trigger_body> include:
o You cannot modify the same relation whose modification is the event triggering the trigger.
o You cannot modify a relation connected to the triggering relation by another constraint such
as a foreign-key constraint.
The clause replace re-creates a previous trigger definition having the same <trigger name>.
The clause replace re-creates a previous trigger definition having the same <trigger name>. The
name of a trigger can be chosen arbitrarily, but it is a good programming style to use a trigger name that
reflects the table and the event(s), e.g., upd ins EMP. A trigger can be invoked before or after the triggering
event. The triggering event specifies before (after) which operations on the table <table> the trigger is
executed. A single event is an insert, an
update, or a delete; events can be combined using the logical connective or. If for an update
trigger no columns are specified, the trigger is executed after (before) <table> is updated. If
the trigger should only be executed when certain columns are upDated, these columns must be specified after
the event update.
OUTPUT:
TRIGGERS
48
10 dbms_output.put_line('table deleted');
11 end if;
12 end;
13 /
SQL> insert into empa values(9,'ram',9000,900,909);
SQL> select * from empa;
SQL> update empa set savings=800 where name='nandhu';
SQL> select * from empa;
SQL> delete from empa where name='kumar';
SQL> select * from empa;
RESULT:
Thus, the triggers has been implemented using PL/SQL.
49
EX.NO:15 XML DATABAS
AIM:
To study the XML database and its types
XML
XML stands for Extensible Markup Language and is a text-based markup language derived from Standard
Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than specifying how to display
it like HTML tags, which are used to display the data. XML is not going to replace HTML in the near future,
but it introduces new possibilities by adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of systems and solutions −
XML is extensible − XML allows you to create your own self-descriptive tags, or language, that
suits your application.
XML carries the data, does not present it − XML allows you to store the data irrespective of how
it will be presented.
XML is a public standard − XML was developed by an organization called the World Wide Web
Consortium (W3C) and is available as an open standard.
XML Database is used to store huge amount of information in the XML format. As the use of XML is
increasing in every field, it is required to have a secured place to store the XML documents. The data stored
in the database can be queried using XQuery, serialized, and exported into a desired format.
XML- enabled
Native XML (NXD)
Example
Following example demonstrates XML database −
<?xml version = "1.0"?><contact-info>
<contact1>
<name>Thivagar </name>
<company>TCS</company>
<phone>(011) 123-4567</phone>
</contact1><contact2>
<name>Manisha </name>
<company>Infosis</company>
<phone>(011) 789-4567</phone>
50
</contact2></contact-info>
Here, a table of contacts is created that holds the records of contacts (contact1 and contact2), which in turn
consists of three entities − name, company and phone.
XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and validate
the structure and the content of XML data. XML schema defines the elements, attributes and data types.
Schema element supports Namespaces. It is similar to a database schema that describes the data in a
database.
Syntax
You need to declare a schema in your XML document as follows −
Example
The following example shows how to use schema −
<?xml version = "1.0" encoding = "UTF-8"?><xs:schema xmlns:xs =
"http://www.w3.org/2001/XMLSchema">
<xs:element name = "contact">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element></xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate format that an XML document can
take.
Conclusion :
Thus the XML database and its types were studied.
51
EX.NO:16 DOCUMENT BASED DATA USING NOSQL DATABASE TOOL
AIM : To study the creation of document based data using Nosql Database Tools
"plot" "A rock band plays their music at high volumes, annoying the neighbors.",
{
"year": 2015,
"title": "The Big New Movie",
"info": {
}
"plot": "Nothing happens at all.",
"rating": 0
}
}
}
The following is an example of a document that might appear in a document
database like MongoDB. This sample document represents a company contact card,
describing
an employee called Sammy:
{
"_id": "sammyshark",
"firstName": "Sammy",
"lastName": "Shark",
52
"email": "sammy.shark@digitalocean.com",
"department": "Finance"
}
Notice that the document is written as a JSON object. JSON is a human-readable data format
that has become quite popular in recent years. While many different formats can be used to
represent data within a document database, such as XML or YAML, JSON is one of the most
common choices. For example, MongoDB adopted JSON as the primary data format to define and
manage data.
All data in JSON documents are represented as field-and-value pairs that take
form of field: value. In the previous example, the first line shows an _id field with the
value sammyshark. The example also includes fields for the employee's first and last names ,their
email address as well as as what department they work in.
Field names allow us to understand what kind of data is held within a document just a
glance. Documents in document databases are self-describing,which
means they contain both the data values as well as the information on what kind of
data is being stored. When retrieving a document from the database, we always get
the whole picture.
Conclusion :
Thus the document based data using Nosql Database Tools were studied.
53
EX.NO :17 BANKING SYSTEM
AIM:
To design and implement any one of the module of Banking system with visual basic as front end and sql
plus as back end.
PROCEDURE :
PROGRAM :
CONCLUSION :
Thus the application program for banking system is done successfully using visual basic as front end
and sql plus as back end.
54