Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DBMS Lab Manual 2017

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

NPR COLLEGE OF ENGINEERING

AND TECHNOLOGY

Name: …………………………………………………….
Year: ….…… Semester: ………. Branch: …………….

University Register No

CERTIFIED that this a Bonafide Record work done by


the above student in the ................................................................
Laboratory during the year .......................20 -20

Signature of the lab Incharge Signature of Head of the Dept.

Date: ………………….

Internal Examiner External Examiner


1
Content
Date Page Date of
Sl.
Name of the Experiment Remarks
No Experiment No. Submission

1. Study of data definition


commands and data
manipulation commands
1a. Study of data control language
and transaction control
statements

2. Database Querying- Simple


Queries, Nested Queries, Sub
Queries And Joins
3. Views, Sequences, Synonyms

4. Database programming: Implicit


and Explicit cursors

5. Implementation of functions in
RDBMS

6. Study of PL/SQL

6a. Implementation of PL/SQL

7. Creation of Procedures

8. Creation of Functions

9. Implementation Of Triggers In
RDBMS
Database Design Using ER
10.
Modeling, Normalization

11. Design And Implementation


Of Banking System.

2
Exp.No:1
STUDY OF DDL AND DML COMMANDS
Date:

AIM:
To execute the Data Definition Language (DDL) commands and Data
Manipulation Language (DML) Commands.

DATA DEFINITION LANGUAGE


1. Creating a Table:
Create command is used to create a table in the database.
Syntax:
create table tablename (column 1 datatype 1, …., column n datatype n);
2. DESC COMMAND
This command is used to view the structure of the table.
Syntax:
desc tablename; (or)
describe tablename;
3. ALTERING A TABLE
The structure of the table can be changed using this command like add
new column, change the width of a datatype, change the datatype of a column.
a.Modify
Syntax:
alter table tablename modify (column datatype, …);
b. Add / Drop
Syntax:
alter table tablename add (column datatype, …);
alter table tablename drop columnname;
4. TRUNCATING A TABLE
This command is used to delete all records stored in a table, but the
structure of the table is retained.

3
Syntax:
truncate table tablename;
5. DROPPING A TABLE
This command is used to remove a table from the database.
Syntax: drop table tablename;

DATA MANIPULATION LANGUAGE


1. INSERT COMMANDS
1. Insert a row with values for columns in a table.
This insert command is used to add rows to a table in the database.
Syntax:
insert into tablename values (value1, value2,……, value n);
insert into tablename(column 1,column 2) values(value 1,value 2);
2. Insert a large number of rows.
This insert command is used to add multiple rows to a table in the
Database in user friendly manner..
Syntax:
insert into tablename values (&column1, &column 2,……, &column n);

2. SELECT COMMANDS
1. Select all rows from a table.
This select command is used to retrieve all the values stored in the table.
Syntax: select * from tablename;
Select column name(s) from tablename;
Select distinct column name from tablename;
2. Select using where command:
This select command is used to retrieve the particular field values, stored
in the table, which satisfy a required condition.
Syntax: select column name(s) from tablename where search condition;
select * from tablename where search condition;

4
3. UPDATE COMMAND
This command is used to update (changing values in) one or two columns
of a row in a table. Specific rows can be updated based on some condition.
Syntax:
update tablename set column1=expression, column 2=expression, ……,
column n=expression;
update tablename set column1=expression, column 2=expression, ……,
column n=expression where search condition;
4. DELETE COMMAND
A delete query is expressed in much the same way as Query. We can delete whole
tuple (rows) we can delete values on only particulars attributes.
1.Deletion of all rows:
Syntax delete from tablename ;

2.Deletion of specified number of rows:


Syntax delete from tablename where search condition ;

Additional Operations performed by DDL and DML Commands:


Creating a table from a table
Syntax
CREATE TABLE TABLENAME [(columnname, columnname, ………)]
AS SELECT columnname, columnname……..FROM tablename;

Elimination of duplicates from the select statement:


Syntax
SELECT DISTINCT columnname, columnname FROM tablename;

Inserting data into a table from another table:


Syntax
INSERT INTO tablename SELECT columnname, columnname, …….
FROM tablename;

Insertion of selected data into a table from another table:


Syntax
INSERT INTO tablename SELECT columnname, columnname……..
FROM tablename WHERE columnname= expression;

Sorting of data in table


Syntax
Select columnname, columnname From table Order by columnname [asc/desc];

5
RENAME COMMAND

Renaming Table name


Syntax rename oldtablename to newtablename;

Renaming columns used with Expression Lists


Syntax
Select columnname result_columnname, Columnname result_columnname from
tablename;

OUTPUT
1. Create EMP table.
SQL>create table emp(empno number(4), ename varchar2(10), job varchar2(9), mgr
number(4), hiredate date, sal number(7,2), comm Number(7,2), deptno number(3), age
number(3), esal number(10));

2.Get the description EMP table.


Name Null? Type
-------------------------------- ----------------------- -------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(3)
AGE NUMBER(3)
ESAL NUMBER(10)

3. Create DEPT table.


SQL>create table dept(deptno number(2) , dname varchar2(14), loc varchar2(13));

4.Get the description DEPT table.


SQL>desc dept;
Name Null? Type
--------------------------------- --------------------- ---------------------------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

5. Insert records into EMP & DEPT.


SQL> insert into emp values(&empno,’&ename’,’&job’,&mgr,’&date’,&sal,&comm.
deptno,&age, &esal);

SQL>insert into dept values(&deptno,’&dname’,’&loc’);

6
6. List all employee details.
SQL>select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO AGE ESAL
----------- ---------- ------ -------- ---------------- ------ ---------- ------------- ------ ----
7369 SMITH CLERK 7902 17-DEC-80 800 0 20 25 0
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 25 0
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 25 0
7566 JONES MANAGER 7839 02-APR-81 2975 500 20 25 0
7698 BLAKE MANAGER 7839 01-MAY-81 2850 1400 30 25 0
7. List all dept details
SQL>select * from dept;
DEPTNO DNAME LOC
------------ ------------ --------
10 accounting New york
20 research Dallas
30 Sales Chicago
40 operations Boston

8. List the employees belonging to the department 20.


SQL> select * from emp where deptno=20;
ENAME
SMITH
JONES
9. List the name and salary of the employees whose salary is more than 1000.
SQL >select ename,sal from emp where sal>1000;
ENAME SAL
----------- --------
ALLEN 1600
WARD 1250
JONES 2975
BLAKE 2850

10. List the names of employees who are managers


SQL >select ename from emp where job = ‘MANAGER’
ENAME
---------
JONES
BLAKE

11. List the different jobs available in employee table.


SQL>select distinct job from emp;
JOB
---------

7
CLERK
MANAGER
SALESMAN
3 rows selected.

12. Alter emp table to add city column which is of string data type.
SQL>Alter table emp add city varchar2(20);
Table altered

13. Alter dept table to change loc column size as 20.


SQL>Alter table dept modify city varchar2(30);
Table altered

14. Update the salary of the employee as 2500 whose job as manager.
SQL>update emp set esal=2500 where job =‘manager’;

15. Delete the employee’s record whose salary is above 2800.


SQL>delete emp where esal>2800;
1 row deleted.

16. Change the name of emp table as EMPLOYEE.


SQL>rename emp to employee;
Table renamed.

17. Delete all records from dept table.


SQL>truncate table dept;
Table truncated.

18. Delete dept table.


SQL>drop table dept;
Table dropped.

RESULT:
Thus the DDL and DML commands are executed successfully.

8
Exp.No:1a
STUDY OF DCL & TCL COMMANDS IN RDBMS
Date:

AIM:
To study Data Control Language statements and Transactional Control Language
statements.

TRANSACTION CONTROL LANGUAGE:


All changes made to the database is defined as a transaction. It is logical unit of
work. The transaction can made permanent to a database only they are committed. A
transaction begins with an executable SQL statement.
The two transaction control commands are:
1. COMMIT
2. SAVEPOINT
3. ROLLBACK
1. COMMIT:
This command is used to make all transaction changes permanent to the database.
Syntax:
COMMIT ;
2. SAVEPOINT:
It is only a marker. Save point are used to divide a lengthy transaction into smaller
ones.
Syntax:
Savepoint id;
3. ROLLBACK:
Rollback commands undo all the changes made in the current transaction.
Syntax:
a. Rollback;
b. Rollback to Savepoint id1;
The first one will rollback (undo) the entire transaction and the last one will undo all
changes made after the creation of the save point id1.

9
DATA CONTROL LANGUAGE:
Data control language, the previous user with privileges commands the database
object (table, view, etc) of a user can’t be accessed by another user without the
permission of a user. The owner can allow other user to access his object as per his
diversion the permission given by a user to another is called privilege.
The Data Control Commands are:
i. GRANT Privilege
ii. REVOKE Privilege
Types of Privilege:
A permission granted to execute the various data definition command like Create
Table, Create Sequence, create session are called System Privilege.
Granting System Privilege:
Grant Command is used to give System Privilege to an oracle user.
Syntax:
GRANT system privilege TO user;
Object Privilege:
An Object Privilege enables a user to execute some commands on the database
object like table view sequence etc.
• Object privileges vary from object to object.
• An owner has all the privileges on the object.
• An owner can give specific privileges on that owner’s object.
Some of the object privileges are
i. Alter
ii. Insert
iii. Update
iv. Delete
v. Select
Syntax:
GRANT object_priv [(columns)]
ON object
TO {user|role|PUBLIC}
[WITH GRANT OPTION];

10
object_priv -- is an object privilege to be granted
ALL --specifies all object privileges
columns --specifies the column from a table or view on which privileges are
granted
ON object -- is the object on which the privileges are granted
TO --identifies to whom the privilege is granted
PUBLIC --grants object privileges to all users
WITH GRANT OPTION --allows the grantee to grant the object privileges to other users and
roles.

Example:
• Grant query privileges on the EMPLOYEES table.
GRANT select ON employees TO itc20,itc30;
Grant succeeded.

• Grant privileges to update specific columns to users and roles.


GRANT update (department_name, location_id) ON departments
TO itc43, itc50;
Grant succeeded.

Give a user authority to pass along privileges.


GRANT select, insert ON departments TO itc45 WITH GRANT OPTION;
Grant succeeded.

Revoking the permission:


Permission granted to a user can also be taken back by the granter. This can be
done by the REVOKE command.
• Privileges granted to others through the WITH GRANT OPTION clause are also
revoked.

Syntax:
REVOKE {privilege [, privilege...]|ALL}
ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];

Example:
REVOKE select, insert ON departments FROM itc20;
Revoke succeeded.

11
OUTPUT :
TCL
SQL> desc stud;
Name Null? Type
----------------------------------------- -------- ----------------------------
SNO NUMBER(3)
SNAME VARCHAR2(10)
BRANCH VARCHAR2(4)

SQL> insert into stud values(01,'Arun','cse');


1 row created.
SQL> insert into stud values(02,'babu','IT');
1 row created.
SQL> commit;
Commit complete.
SQL> select * from stud;
SNO SNAME BRAN
---------- ---------- ----
1 Arun cse
2 babu IT
SQL> insert into stud values(03,'chitra','IT');
1 row created.
SQL> select * from stud;
SNO SNAME BRAN
---------- ---------- ----
1 Arun cse
2 babu IT
3 chitra IT
SQL> rollback;
Rollback complete.

12
SQL> select * from stud;
SNO SNAME BRAN
---------- ---------- ----
1 Arun cse
2 babu IT
SQL> savepoint s1;
Savepoint created.
SQL> insert into stud values(04,'Devi','CSE');
1 row created.
SQL> select * from stud;
SNO SNAME BRAN
---------- ---------- ----
1 Arun cse
2 babu IT
4 Devi CSE

SQL> rollback to s1;


Rollback complete.
SQL> select * from stud;
SNO SNAME BRAN
---------- ---------- ----
1 Arun cse
2 babu IT

DCL
User it2a40:
SQL> grant all on student to it2a36;
Grant succeeded.
User it2a36:
SQL> select * from it2a40.student;

13
ROLL_NO NAME DEPT SEM1 SEM2 SEM3
---------- ------------ ---------- ---------- ---------- ----------
1 alex ece 92.3 90.5 89.3
2 bala ece 88.2 85 89.3
3 booba it 91.1 85 93
insert into it2a40.student values(&roll_no,'&name','&dept',&sem2,&sem2,&sem3);
Enter value for roll_no: 4
Enter value for name: chitra
Enter value for dept: it
Enter value for sem2: 88.5
Enter value for sem2: 90
Enter value for sem3: 92
old 1: insert into it2a40.student
values(&roll_no,'&name','&dept',&sem2,&sem2,&sem3)
new 1: insert into it2a40.student values(4,'chitra','it',88.5,90,92)
1 row created.
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3
---------- --------------- ---------- ---------- ---------- ----------
4 chitra it 88.5 90 92
1 alex ece 92.3 90.5 89.3
2 bala ece 88.2 85 89.3
3 booba it 91.1 85 93
SQL> alter table it2a40.student add(avg number(10,3));
Table altered.
SQL> update it2a40.student set avg=91.2 where roll_no=1;
1 row updated.
SQL> update it2a40.student set avg=88.5 where roll_no=2;
1 row updated.
SQL> update it2a40.student set avg=89.9 where roll_no=3;
1 row updated.

14
SQL> update it2a40.student set avg=90.2 where roll_no=4;
1 row updated.

SQL> select * from it2a40.student;


ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG
---------- --------------- ---------- ---------- ---------- ---------- -------------------------------
4 chitra it 88.5 90 92 90.2

1 alex ece 92. 90. 9 89.3 91.2

2 bala ece 88.2 85 89.3 88.5

3 booba it 91.1 85 93 89.9

SQL> delete from it2a40.student where roll_no=4;


1 row deleted.
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG
---------- --------------- ---------- ---------- ---------- ----------------------------------------
1 alex ece 92.3 90.5 89.3 91.2
2 bala ece 88.2 85 89.3 88.5
3 booba it 91.1 85 93 89.9

User it2a40:
SQL> revoke delete on student from it2a36;
Revoke succeeded.

User it2a36:
SQL> delete from it2a40.student where roll_no=2;
delete from it2a40.student where roll_no=2
*
ERROR at line 1:
ORA-00942: table or view does not exist

User it2a40:
SQL> revoke all on student from it2a36;

15
Revoke succeeded.

User it2a36:
SQL> select * from it2a40.student;
select * from it2a40.student

User it2a40:
SQL> grant select on student to it2a36;
Grant succeeded.

User - it2a36:
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG
---------- --------------- ---------- ---------- ---------- ----------------------------------------
1 alex ece 92.3 90.5 89.3 91.2
2 bala ece 88.2 85 89.3 88.5
3 booba it 91.1 85 93 89.9

User it2a40:
SQL> revoke select on student from it2a36;
Revoke succeeded.

RESULT:
Thus the study of DCL commands and TCL commands was performed
successfully.

16
Exp.No:2 DATABASE QUERYING-SIMPLE QUERIES, NESTED
Date: QUERIES, SUB QUERIES AND JOINS
AIM:
To query simple, nested, sub queries and joins
SET OPERATIONS:
The SET operators combine the results of two or more component queries into
one result. Queries containing SET operators are called compound queries. Some of set
operators are,
UNION - Rows of first query plus rows of second query
UNION ALL - Rows of first query plus rows of second query, including all duplicates
INTERSECT – common rows from all queries
MINUS - All distinct rows that are selected by the first SELECT statement and not
selected in the second SELECT statement
Syntax:
select query set operator select query
JOINS:

An SQL join clause combines records from two or more tables in a database. It
creates a set that can be saved as a table or used as is. A JOIN is a means for combining
fields from two tables by using values common to each. ANSI standard SQL specifies
four types of Joins: INNER, OUTER, LEFT, and RIGHT. As a special case, a table (base
table, view, or joined table) can JOIN to itself in a self-join.

A programmer writes a JOIN predicate to identify the records for joining. If the
evaluated predicate is true, the combined record is then produced in the expected format,
a record set or a temporary table.

SQL specifies two different syntactical ways to express joins: "explicit join
notation" and "implicit join notation".

The "explicit join notation" uses the JOIN keyword to specify the table to join,
and the ON keyword to specify the predicates for the join.

17
The "implicit join notation" simply lists the tables for joining (in the FROM
clause of the SELECT statement), using commas to separate them
Inner Join
Inner join creates a new result table by combining column values of two tables (A
and B) based upon the join-predicate. The query compares each row of A with each row
of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a
result row. The result of the join can be defined as the outcome of first taking the
Cartesian product (or Cross join) of all records in the tables (combining every record in
table A with every record in table B)—then return all records which satisfy the join
predicate. Inner join is further classified as equi-joins, as natural joins, or as cross-joins
Syntax:
Explicit Notation:
Select * from table name1 inner join table name2 on table1.fieldname=table2.fieldname;
Select * from table1 inner join table2 using(fieldname);
Implicit Notation
Select * from table1, table2 where table1.fieldname=table2.fieldname;

Equi Join

An equi-join is a specific type of comparator-based join, or theta join that uses


only equality comparisons in the join-predicate. Using other comparison operators (such
as <) disqualifies a join as an equi-join. The query shown above has already provided an
example of an equi-join:

Syntax:

Explicit Notation:

Select * from table1 join table2 on table1.fieldname=table2.fieldname;


Natural join
A natural join offers a further specialization of equi-joins. The join predicate
arises implicitly by comparing all columns in both tables that have the same column-

18
names in the joined tables. The resulting joined table contains only one column for each
pair of equally-named columns
Explicit Notation:
Select * from table1 natural join table2 on table1.fieldname=table2.fieldname;

Cross join

Cross Join returns the Cartesian product of rows from tables in the join. In other
words, it will produce rows which combine each row from the first table with each row
from the second table.
Explicit Notation:
Select * from table1 cross join table2 ;
Implicit Notation
Select * from table1,table2;

Outer joins

An outer join does not require each record in the two joined tables to have a
matching record. The joined table retains each record—even if no other matching record
exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer
joins, depending on which table(s) one retains the rows from (left, right, or both).

Left outer join

The result of a left outer join (or simply left join) for table A and B always
contains all records of the "left" table (A), even if the join-condition does not find any
matching record in the "right" table (B). This means that a left outer join returns all the
values from the left table, plus matched values from the right table (or NULL in case of
no matching join predicate).

Explicit Notation:
Select * from table1 left outer join table2 on table1.fieldname=table2.fieldname

19
Implicit Notation

SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column =


table2.column (+);

Right outer join

A right outer join (or right join) closely resembles a left outer join, except with the
treatment of the tables reversed. Every row from the "right" table (B) will appear in the
joined table at least once. If no matching row from the "left" table (A) exists, NULL will
appear in columns from A for those records that have no match in B.

Explicit Notation:
Select * from table1 right outer join table2 on table1.fieldname=table2.fieldname

Implicit Notation

SELECT table1.column, table2.column FROM table1, table2 WHERE


table1.column(+) = table2.column;

Full outer join

Conceptually, a full outer join combines the effect of applying both left and right
outer joins. Where records in the FULL OUTER JOINed tables do not match, the result
set will have NULL values for every column of the table that lacks a matching row.

Explicit Notation:
Select * from table1 full outer join table2 on table1.fieldname=table2.fieldname

Self-join

A self-join is joining a table to itself means each row of the table is combined
with itself and with every other row of the table. The self join is viewed as join of two
copies of the same table.

20
SET OPERATIONS
1. Display the different designation in department 20 and 30.
SQL> select designation from emp where deptno=20
union
select designation from emp where deptno=30;

SQL> select designation from emp where deptno=20 union all select designation from
emp where deptno=30;

2. List the jobs common to department 20 and 30.


SQL> select designation from emp where deptno=20 intersect select designation from
emp where deptno=30;

3. List the jobs unique to department 20.


SQL> select designation from emp where deptno=20 minus select designation from emp
where deptno=10 minus select designation from emp where deptno=30;

(Or)
SQL> select designation from emp where deptno=20 minus select designation from emp
where deptno in (10,30);

JOINS:
Tables:
SQL> create table two(deptno number(4) primary key,deptname varchar(10));
Table created.

SQL> create table one(name varchar(10),deptno references two(deptno));


Table created.
Insert these values into table one and table two

SQL> select * from one;


NAME DEPTNO
---------- ----------
anand 31
babu 32
chitra 32

3 rows selected.

SQL> select * from two;


DEPTNO DEPTNAME
---------- ----------
31 sales
32 enggg

21
Inner join
i.SQL> select * from one, two where one.deptno=two.deptno;

ii.SQL> select * from one inner join two on one.deptno=two.deptno

Equi join
i.SQL> select * from one join two on one.deptno=two.deptno;

ii.SQL> select * from one inner join two using(deptno);

Natural join
i.SQL> select * from one natural join two;

Cross Join
i.SQL> select * from one cross join two;

ii.SQL> select * from one,two;

Left outer join


i.SQL> select * from one left outer join two on one.deptno=two.deptno;

ii. SQL> select * from one,two where one.deptno=two.deptno(+);

Right outer join


i. SQL> select * from one right outer join two on one.deptno=two.deptno;

ii. SQL> select * from one,two where one.deptno(+)=two.deptno;

Full outer join


i.SQL> select * from one full outer join two on one.deptno=two.deptno;

Self join
SQL> create table selfj(empno number(5),ename varchar(7),mgr number(5));
Table created.

Insert values for table selfj

SQL> select * from selfj;


EMPNO ENAME MGR
---------- ------- ----------
7839 kalyan
7566 jones 7839
7876 anand 7788
7934 babu 7782
7777 raja 7934

22
List out the names of manager with the employee record.
SQL> select worker.ename,manager.ename from selfj worker,selfj manager where
worker.mgr=manager.empno;

SUBQUERIES
A subquery is a SELECT statement that is embedded in a clause of another
SELECT statement. You can build powerful statements out of simple ones by using
subqueries. A Common use of subquery is to perform tests for
1.set memberships,
2.setcomparisons
3.set cardinality.

 The subquery (inner query) executes once before the main query.
 The result of the subquery is used by the main query (outer query).
 A subquery must be enclosed in parentheses.
 Place the subquery on the right side of the comparison condition for readability.

Note: Comparison conditions fall into two classes:


1. single-row operators (>, =, >=, <, <>, <=) and
2. multiple-row operators (IN, ANY, ALL).
The subquery is often referred to as a nested SELECT, sub-SELECT, or inner
SELECT statement. The subquery generally executes first, and its output is used to
complete the query condition for the main or outer query.

Subquery Syntax
SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM
table);

Types of Subqueries

• Single-row subqueries: Queries that return only one row from the inner SELECT
statement
• Multiple-row subqueries: Queries that return more than one row from the inner
SELECT Statement.

23
A single-row subquery
Subqueries that returns one row from the inner SELECT statement. This type of
subquery uses a single-row operator.

Multiple-Row Subqueries
Subqueries that return more than one row are called multiple-row subqueries. You
use a multiple-row operator, instead of a single-row operator, with a multiple-row
subquery. The multiple-row operator expects one or more values.

QUERIES:
1.Select loanno, branchname, amount from loan where amount=(select min(amount) from
loan)

2. Select sname, rollno, dept, marks from student where marks=(select min(marks) from
student group by dept;

3. Select sname, rollno, dept, marks from student where marks IN (select min(marks)
from student group by dept)

4. Select sname, rollno, dept, marks from student where marks NOT IN (select
min(marks) from student)

24
5. select * from loan where amount > ANY (select amount from loan where
branchname=’chennai’)

6. select * from loan where amount > ALL (select amount from loan where
branchname=’chennai’)

7. select * from loan where EXISTS (select * from borrower where


loan.loanno=borrower.loanno)

8. select * from loan where NOT EXISTS (select * from borrower where
loan.loanno=borrower.loanno)

9. select * from loan where EXCEPT (select * from borrower where


loan.loanno=borrower.loanno)

10. Find all customers who have both an account and a loan at the bank.
Select distinct cusname from customer where cusname IN (select cusname from
depositor)

11. Find all customers who have a loan at the bank but do not have an account at
the bank.
Select distinct cusname from customer where cusname NOT IN (select cusname from
depositor)

12. Find the loanno,amount,branchname who have get second maximum loan
amount at the bank.
Select loanno, branchname, max(amount) from loan where amount<=(select
max(amount) from loan )

13. Write a query that displays the roll numbers and student names of all student
who studied in a department with any student whose name contains a S.
SELECT rollno, sname FROM student WHERE dept IN (SELECT dept FROM student
WHERE sname like ’%s%’);

14. List the employee names whose salary is greater than the lowest salary of an
employee belonging to department number 30.
SQL> select ename from emp
where sal>any
(select sal from emp where deptno=30);

15. List the employee details of those employees whose salary is greater than any of
the salesman.
SQL> select empno, ename, sal from emp where sal>any(
select sal from emp where job='asstprof');

25
16. List the employee names whose salary is greater than the highest salary of an
employee belonging to department number 20.
SQL> select ename from emp
where sal>all(select sal from emp where deptno=20);

RESULT:

Thus the database querying for simple, nested, sub queries and joins were
performed successfully.

26
Exp.No:3
VIEWS, SEQUENCES, SYNONYMS
Date:

AIM:
To study about views, sequences, synonyms and execute them.

Views
(i) Logically represents subsets of data from one or more tables.
(ii) You can present logical subsets or combinations of data by creating views of tables. A
view is a logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or changed. The
tables on which a view is based are called base tables. The view is stored as a SELECT
statement in the data dictionary.
Why Use Views?
• To restrict data access
• To make complex queries easy
• To provide data independence
• To present different views of the same data.
Advantages of Views
1. Data security
2. Simplicity
3. Structural Simplicity
Simple Views versus Complex Views
There are two classifications for views: simple and complex. The basic difference is
related to the DML (INSERT, UPDATE, and DELETE) operations.
• Simple view
– Derives data from only one table
– Contains no functions or groups of data
– Can perform DML operations through the view
• Complex view
– Derives data from many tables
– Contains functions or groups of data

27
– Does not always allow DML operations through the view
Creation of Views:
Syntax
CREATE VIEW viewname AS
SELECT columnname1, columnname2
FROM tablename
WHERE columnname=expression_list;

Example:
CREATE VIEW empvu80
AS SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 80;
View created.

Assigning Names to Columns


Syntax
CREATE VIEW viewname(newcoluname1, newcoluname2) AS
SELECT columnname1, columnname2
FROM tablename
WHERE columnname=expression_list;

Example:
* Create a view by using column aliases in the
subquery.

CREATE VIEW salvu50


AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
View created.
(or)
CREATE VIEW salvu50(ID_NUMBER,NAME,ANN_SALARY)
AS SELECT employee_id , last_name ,
salary*12
FROM employees
WHERE department_id = 50;
View created.

• Describe the structure of the view


Example:
DESCRIBE empvu80

Retrieving Data from a View


Example:
28
SELECT * FROM salvu50;
Destroying a view:
Syntax
DROP VIEW viewname;
Example:
DROP VIEW salvu50;

Modifying a View

CREATE OR REPLACE VIEW empvu80


(id_number, name, sal, department_id)
AS SELECT employee_id, first_name || ’ ’ || last_name,
salary, department_id
FROM employees
WHERE department_id = 80;
View created.

Creating a Complex View

CREATE VIEW dept_sum_vu


(name, minsal, maxsal, avgsal)
AS SELECT d.department_name, MIN(e.salary),
MAX(e.salary),AVG(e.salary)
FROM employees e, departments d
WHERE e.department_id = d.department_id
GROUP BY d.department_name;
View Created;

QUERIES:
1. Create view on emp table whose sal is less than 2000.
SQL>create view salamt_view as select * from emp where sal<2000;
2. Create a view dept_view on dept table and rename the columns as dno,
deptname,location respectively.
SQL>create view dept_view as select deptno, dname, loc from dept;
3. Select the employee names from salamt_view whose job is assistant prof.
SQL>select name from salamt_view where trim(job)='Asstprof';
4. Drop the view salamt_view.
SQL>drop view salamt_view;

29
SEQUENCES
Oracle provides the capability to generate sequences of unique numbers, and they
are called sequences.
Just like tables, views, indexes, and synonyms a sequence is a type of database
object.
Sequences are used to generate unique, sequential integer values that are used as
primary key values in database tables.
The sequences of numbers can be generated in either ascending or descending
order.

QUERIES:
Creation of table
SQL>create table class(name varchar(10),id number(10));
Table created.

Inserting values
SQL>insert into class values(‘&name’,&id);
Enter value for name: anu
Enter value for id:1
Old 1:insert into class values(‘&name’,’&id)
New 1:insert into class values(‘anu’,1)
1 row created.

SQL>/
Enter value for name: brindha
Enter value for id:2
Old 1: insert into class values(‘&name’,’&id)
New 1: insert into class values(‘brindha’,2)
1 row created.

SQL>/
Enter value for name: chinna
Enter value for id:3
Old 1: insert into class values(‘&name’,’&id)
New 1: insert into class values(‘chinna’,3)
1 row created.

SQL>select * from class;


Name id
--------------------
Anu 1
Brindha 2
China 3

30
Create sequence
SQL> create sequence S
starts with 4
increment by 1
maxvalue 100
cycle;
sequence created.
SQL>insert into class values(‘diya’,s.nextval);
1 row created.
SQL> select * from class;
Name id
--------------------
Anu 1
Brindha 2
China 3
Diya 4

Alter sequence
SQL> alter sequence s
increment by 2;
sequence altered.
SQL>insert into class values(‘www’,s.nextval);
1 row created.
SQL> select * from class;
Name id
--------------------
Anu 1
Brindha 2
China 3
Diya 4
www 6

DROP SEQUENCE
SQL> drop sequence s;
Sequence dropped.

SYNONYMS
A synonym is an alias, that is, a form of shorthand used to simplify the task of
referencing a database object.
There are two categories of synonyms, public and private.
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.

31
Queries:

SQL>create synonym c1 for class;


Synonym created.

SQL>insert into c1 values (‘kalai’,20);


1 row created.

SQL>select * from c1;

Name id
--------------------
Anu 1
Brindha 2
China 3
Diya 4
www 6
kalai 20
8 rows selected.

Drop synonym
SQL> drop synonym c1;
Synonym dropped.

RESULT:
Thus the SQL commands for views, sequences, and synonyms were executed and
the outputs were verified.

32
Exp.No:4 DATABASE PROGRAMMING:IMPLICIT AND EXPLICIT
Date: CURSORS

AIM:
To study about implicit and explicit cursors and execute them.

INTRODUCTION

A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL statement.
The set of rows the cursor holds is referred to as the active set.

You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors
 Implicit cursors
 Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement
is executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an


implicit cursor is associated with this statement. For INSERT operations, the cursor
holds the data that needs to be inserted. For UPDATE and DELETE operations, the
cursor identifies the rows that would be affected.

PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor,
which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use
with the FORALL statement.

The following table provides the description of the most used attributes –

33
S.NO ATTRIBUTE & DESCRIPTION
1.
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one
or more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.
2.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT,
UPDATE, or DELETE statement affected no rows, or a SELECT INTO
statement returned no rows. Otherwise, it returns FALSE.
3.
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
4.
%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown


below in the example.

Example
We will be using the CUSTOMERS table we had created and used in the
previous chapters.

QUERIES

Creating table:

Create table customers(id number(6),name varchar(6),age number(7),address


varchar(8),salary number(8));
Select * from customers;
ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
34
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each
customer by 500 and use the SQL%ROWCOUNT attribute to determine the number of
rows affected −
PROGRAM

DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
PL/SQL procedure successfully completed.

If you check the records in customers table, you will find that the rows have been updated

Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |

Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the
context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
Syntax
CURSOR cursor_name IS select_statement;

35
Working with an explicit cursor
includes the following steps −
Declaring the cursor for initializing the memory
Opening the cursor for allocating the memory
Fetching the cursor for retrieving the data
Closing the cursor to release the allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −

CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we will open the
above defined cursor as follows –

OPEN c_customers;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time. For example, we will fetch
rows from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will
close the above-opened cursor as follows −
CLOSE c_customers;

PROGRAM

DECLARE
c_id customers.id%type;
c_name customerS.No.ame%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;

36
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Output
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL procedure successfully completed.

RESULT:
Thus the database programming for implicit cursors and explicit cursors were
executed successfully.

37
Exp.No:5
STUDY OF FUNCTIONS IN RDBMS
Date:
AIM:
To Study single row functions (character, numeric, date functions), group
functions and operators in RDBMS.

THEORY & CONCEPTS:


I. SINGLE ROW FUNCTIONS:
Number Functions:
You can manipulate retrieved numbers by rounding up to specific precessions or
perform extra calculation functionalities. SQL has several number functions that you can
use to manipulate retrieved numbers. The following are list of some numeric functions.
Function Description
ABS(number) Returns the absolute value of a number
CEIL(number) Rounds up the number to next integer
FLOOR(number) Rounds down the number to next integer
MOD(number, divisor) Returns the remainder of a division
POWER(number, power) Returns of number raised specified power
SQRT(number) Returns the square root of a number

String Functions:

Function Description
CONCAT(string1, string2) Concatenates two strings
INITCAP(string) Returns strings with first letter in upper case
LENGTH (string) Returns an integer representing the string length
LTRIM(string,serachSrting) Remove character from left/ right of char
RTRIM(string,serachSrting)
UPPER(string) Returns string with all upper/ lower case characters
Lower(string)
SUBSTR(string,start,length) Returns substring starting at start &of specified length
REPLACE(string,searchstring,replacement) REPLACE returns char with every
occurrence of search String replacement String

DateFunctions:

Function Description
SYSDATE Returns current date
ADD_MONTHS Returns date retrieved date added to specified month
LAST_DAY (Date) Returns date that is last day of the month
MONTHS_BETWEEN( Date1,Date2) Returns months between two dates specified months

38
DATE FUNCTIONS

1. SQL> select add_months (sysdate, 3) from dual;

2. SQL> select add_months('3_jan_08',4) from dual;

3. SQL> select months_between (’12-jul-07’,’03-nov-07’) from dual;

4. SQL> select next_day (’03-nov-07’,’tuesday’) from dual;

5. SQL> select last_day (’03-nov-07’) from dual;

6. SQL> select to_char (sysdate, ’ddth month yyyy’) from dual;

7. SQL> select to_date (’03-nov-07’, ’ddth month yyyy’) from dual;

8. SQL> select greatest('27_jan_04','27_jun_04') from dual;

9. SQL> select sysdate from dual;

CHARACTER FUNCTIONS

10. SQL> select initcap (‘rameeze’) from dual;

11. SQL> select lower (‘rAMEEzE’) from dual;

12. SQL> select upper (‘rameeze’) from dual;

13. SQL> select ltrim (‘rameeze’,’ram’) from dual;

14. SQL> select rtrim (‘Rameeze’,’eeze’) from dual;

15. SQL> select replace (‘wing’,’w’,’K’) from dual;

16. SQL> select substr (‘Rameeze’, 0, 3) from dual;

17. SQL> select lpad('xxxyyvvv',10)from dual;

18. SQL> select rpad('xxxyyvvv',10)from dual;

19. SQL> select concat('Database','System')from dual;

20. SQL> select instr('abac','a',1,1) from dual;

21. SQL> select length('data') from dual;

39
NUMERIC FUNCTIONS

22. SQL> select abs (-50) from dual;

23. SQL> select cos (0) from dual;

24. SQL> select exp (3) from dual;

25. SQL> select power (3,3) from dual;

26. SQL> select mod (9,3) from dual;

27. SQL> select sqrt (9) from dual;

28. SQL> select floor(435.00) from dual;

29. SQL> select trunc(100.02345,2) from dual;

30. SQL> select ceil(100.01) from dual;

31. SQL> select sin(45) from dual;

32. SQL> select round(2.3) from dual;

33. SQL> select round(2.5) from dual;

II. GROUP FUNCTIONS


Unlike single-row functions, group functions operate on sets of rows to give one
result per group. These sets may be the whole table or the table split into groups.

Types of Group Functions


• AVG
• COUNT
• MAX
• MIN
• STDDEV
• SUM
• VARIANCE
Function Description
Each of the functions accepts an argument. The following table identifies the options that
you can use in the syntax:

40
GROUP FUNCTIONS & OPERATORS

1. List all employee names and their salaries, whose salary lies between
1500/- and 3500/- both inclusive.
SQL>select ename from emp where salary between 1500 and 3500;

2. List all employee names and their manager whose jobid is


7902 or 7566 0r 7789.
SQL>select ename from emp where jobid in(7602,7566,7789);

3. List all employees which starts with either J or T.


SQL>select ename from emp where ename like ‘J%’ or ename like ‘T%’;

4. List all employee names and jobs, whose job title includes M or P.
SQL>select ename, designation from emp where designation like ‘M%’ or job
like ‘P%’;

5. List all jobs available in employee table.


SQL>select distinct designation from emp;

6. List all employees who belongs to the department 10 or 20.


SQL>select ename from emp where deptno in (10,20);

41
7. List all employee names , salary and 15% rise in salary.
SQL>select ename , salary , salary+0.15* salary from emp;

8. List minimum , maximum , average salaries of employee.


SQL>select min(salary),max(salary),avg(salary) from emp;

9. Find how many job titles are available in employee table.


SQL>select count (distinct designation) from emp;

10. What is the difference between maximum and minimum salaries of employees in
the organization?
SQL>select max(salary)-min(salary) from emp;

11. Find how much amount the company is spending towards salaries.
SQL>select sum (salary) from emp;

12. Display name of the dept. with deptno 20.


SQL>select ename from emp where deptno = 20;

13. List ename whose commission is NULL.


SQL>select ename from emp where comm is null;

14. Find no.of dept in employee table.


SQL>select count (distinct ename) from emp;

15. List ename whose manager is not NULL.


SQL>select ename from emp where jobid is not null;

16. Display total salary spent for each job category.


SQL>select designation, sum (salary) from emp group by designation;

17. Display number of employees working in each department and their


Department name.

42
SQL> select dname, count (ename) from emp, dept where
emp.deptno=dept.deptno
group by dname;

18.List the employee details in ascending order of salary.


SQL> select empno, ename, salary from emp order by sal;

19. List the employee name and hiredate in descending order of hiredate.
SQL> select ename, hiredate as doj from emp order by 2 desc;

20.List the job and salary of employees job wise for department number 30 and
display only those rows having salary greater than 1500 .
SQL> select designation, salary from emp where deptno=30 group by designation
having salary >1500;

RESULT:
Thus the study of single row functions, group functions were performed
successfully.

43
Exp.No:6
STUDY OF PL/SQL
Date:

Aim:
To study the basics of PL/SQL.

Theory & Concepts:

PL/SQL is the procedural extension to SQL with design features of programming


languages. Data manipulation and query statements of SQL are included within procedural
units of code.
Benefits of PL/SQL:

PL/SQL can improve the performance of an application. The benefits differ


depending on the execution environment:
 PL/SQL can be used to group SQL statements together within a single block and
to send the entire block to the server in a single call thereby reducing networking traffic.
Without PL/SQL, the SQL statements are sent to the Oracle server one at a time. Each
SQL statement results in another call to the Oracle server and higher performance
overhead. In a network environment, the overhead can become significant.
 PL/SQL can also operate with Oracle server application development tools such
as Oracle forms and Oracle reports.
PL/SQL Block Structure:

Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely
separate or nested one within another. The basic units (procedures, functions, and
anonymous blocks) that make up a PL/SQL program are logical blocks which can contain
any number of nested sub-blocks. Therefore one block can represent a small part of
another block, which in turn can be part of the whole unit of code.
Identifiers/Variables:

In PL/SQL, you can use identifiers to do the following:


 Declare variables, cursors, constants and exceptions and then use them in SQL
and procedural statements.

44
 Declare variables belonging to scalar, reference, composite and large object
(LOB) data types.
 Declare variables dynamically based on the data structure of tables and columns
in the database.

PL/SQL Block Syntax:

DECLARE [Optional]
Variables, cursors, user defined exceptions
BEGIN [Mandatory]
- SQL Statements –
- PL/SQL Statements –
Exception [Optional]
-- Actions to be performed when errors occur ----
END [Mandatory];

Anonymous, procedure and function blocks:

Anonymous:
- No name.
- Starts with DECLARE statement.

Procedure:
- No return.
- PROCEDURE name IS

Function:
- Returns a value
- FUNCTION name RETURN data-type IS

Programming Constructs:

Declaring Variables:

Identifier [CONSTANT] data-type [NOT NULL] [:= | DEFAULT expr];

Assignment:
Identifier := expr;

IF Statement:

IF condition THEN
Statements;

45
[ELSE IF condition THEN
Statements;]
[ELSE
Statements;]
END IF;

CASE Statement:

CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
....
....
WHEN expression THEN resultn
[ELSE resultn1;]
END;

BASIC Loops:

LOOP
Statement 1;
....
....
EXIT [WHEN condition];
END LOOP;

WHILE Statement:
WHILE condition LOOP
Statement1;
....
....
END LOOP;

FOR Statement:
FOR counter IN [REVERSE]
Lower_bound..upper_bound LOOP
Statement1;
....
....
END LOOP;

RESULT:
Thus the basics of PL/SQL was studied

46
Exp.No:6a
IMPLEMENTATION OF PL/SQL
Date:

AIM:
To implement the PL/SQL block that satisfy some conditions by accepting input
from the user.

i.)Write a program in PL/SQL for addition of two numbers.


SQL>declare
no1 number:=&a;
no2 number:=&b;
begin
dbms_output.put_line('Sum:'||(no1+no2));
end;
/
Enter value for a: 10
old 2: no1 number:=&a;
new 2: no1 number:=10;
Enter value for b: 2
old 3: no2 number:=&b;
new 3: no2 number:=2;
Sum:12

PL/SQL procedure successfully completed.

ii.)Write a program in PL/SQL for addition of 1 to 100 numbers.


Declare
a number;
s1 number default 0;
Begin
a:=1;
loop
s1:=s1+a;
exit when (a=100);
a:=a+1;
end loop;
dbms_output.put_line('Sum between 1 to 100 is '||s1);
End;
/
Sum between 1 to 100 is 5050

PL/SQL procedure successfully completed.

47
iii.)Write a program in PL/SQL for Reverse of a Number

declare
n number;
rev number:=0;
r number;
begin
n:=&n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;
dbms_output.put_line('reverse is '||rev);
end;
/
Enter value for n: 1235
old 8: n:=&n;
new 8: n:=1235;
reverse is 5321

PL/SQL procedure successfully completed.

RESULT:

Thus the PL/SQL programs were written and executed to accept the input from
the users.

48
Exp.no:7
CREATION OF PROCEDURES
Date:

Aim:
To create and implement the PL/SQL procedures.

QUERIES:

i.)Create a stored procedure which takes empno as parameter, and display the name
and job of the employee.
SQL>create or replace procedure emppro(eno in number)is
begin
for v in (select * from emp where empno=eno)
loop
dbms_output.put_line('Name: '||v.ename||' Designation: '||v.designation);
end loop;
end;
/
Procedure created.

OUTPUT:
SQL> exec emppro('7369');
Name: Smith Designation:Clerk

PL/SQL procedure successfully completed.

ii.)Create a stored procedure which takes employee’s job as parameter, and display
the details of the all employees with salary greater than max salary.
create or replace procedure max(s in varchar2)is
begin
for v in (select * from emp where sal>
all(select sal from emp where job=s))
loop
dbms_output.put_line('Name: '||v.ename||' Salary: '||v.sal);
end loop;
end;
/
Procedure created.
OUTPUT:
SQL> exec max('Salesman');
Name: jones Salary: 2975
Name: blake Salary: 2850
PL/SQL procedure successfully completed.

49
iii.)Create a procedure that location for the given department number.
create or replace procedure loc(no in number)is
begin
for v in (select * from dept where deptno=no)
loop
dbms_output.put_line('Department Number: '||v.deptno||'Location: '||v.loc);
end loop;
end;/
Procedure created.

declare
no number;
begin
no:=&a;
loc(no);
end;/
Enter value for a: 10
old 4: no:=&a;
new 4: no:=10;
Department Number:10 Location: New york
PL/SQL procedure successfully completed.

Result:

Thus the above given queries were solved using procedures.

50
Exp.no:8
CREATION OF FUNCTIONS
Date:

Aim:
To create and implement the PL/SQL functions.

QUERIES:

i.)Write a function in PL/SQL to check the given number is even or odd.


create or replace function nochk(no number)return varchar2 is
status varchar2(20);
begin
if(mod(no,2)=0)
then
status:='Even';
else
status:='Odd';
end if;
return status;
end;
/
Function created.

declare
n number(2);
begin
n:=&a;
dbms_output.put_line('Number is '||nochk(n));
end;
/
Enter value for a: 19
old 4: n:=&a;
new 4: n:=19;
Number is Odd
PL/SQL procedure successfully completed.

ii.) Write a function in PL/SQL to multiply the given number.


SQL> create or replace function F1 (n number)
return number is
k number;
begin
k: = n*100;
return k;

51
end;
/

OUTPUT:
function created.

SQL> select F1(3) from dual;

F1 (3)
300

iii.)
SQL> create or replace function F2 (a number)
return char is
o varchar 2(25):= ‘The number is odd’;
e varchar 2(25):= ‘The number is even’;
r number;
begin
r: = mod (a, 2);
if r=0 then return e;
else
return o;
endif;
end;
/

OUTPUT:
function created.

SQL> select F2 (9) from dual;

F2 (9)
The number is odd.

iv.) Create a procedure to update the salary for the employee based on their job. The
main procedure should contain update statement. The main procedure should call
second procedure that contain rate of employee.
SQL>create or replace function rate_sub(s in varchar2)return number is
rate number(2);
begin
if(trim(s)='clerk') then
rate:=0.2;
else
rate:=0.1;

52
end if;
return rate;
end;/

Function created.

Main Procedure:
create or replace procedure rate_main(s in varchar2) is
rate number(2);
begin
for a in(select * from emp where job=s)
loop
rate:=rate_sub(s);
update emp set sal=sal+(sal*rate) where job=s;
dbms_output.put_line('Name: '||a.ename||' Salary: '||a.sal);
end loop;
end;
/
Procedure created.

OUTPUT:
SQL> exec rate_main('salesman');
Name: Allen Salary: 1600
Name: Ward Salary: 1250

PL/SQL procedure successfully completed.

Result:
Thus the above given queries were solved using functions.

53
Exp.No:9
IMPLEMENTATION OF TRIGGERS IN RDBMS
Date:

AIM:
To implement the concept of Trigger.

Theory & Concepts:

Database Triggers:

Database triggers are procedures that are stored in the database and are implicitly
executed (fired) when the contents of a table are changed.

Use of Database Triggers:

Database triggers support Oracle to provide a highly customized database


management system. Some of the uses to which the database triggers can be put to
customize management information in Oracle are as follows:-
• A Trigger can permit DML statements against a table any if they are issued, during
regular business hours or on predetermined weekdays.
• A trigger can also be used to keep an audit trail of a table along with the operation
performed and the time on which the operation was performed.
• It can be used to prevent invalid transactions.
• Enforce complex security authorizations.

How to apply Database Triggers:


A trigger has three basic parts:
1. A triggering event or statement.
2. A trigger restriction
3. A trigger action.

Types of Triggers:

Using the various options , four types of triggers can be created:

1. Before Statement Trigger:


Before executing the triggering statement, the trigger action is executed.

54
2. Before Row Trigger:
Before modifying the each row affected by the triggering statement and before appropriate
integrity constraints, the trigger is executed if the trigger restriction either evaluated to
TRUE or was not included.
3. After Statement Trigger:
After executing the triggering statement and applying any deferred integrity constraints,
the trigger action is executed.
4. After row Trigger:
After modifying each row affected by the triggering statement and possibly applying
appropriate integrity constraints, the trigger action is executed for the current row if the
trigger restriction either evaluates to TRUE or was not included.

Elements in a Trigger:

 Trigger timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
 Trigger event: INSERT, UPDATE, OR DELETE
 Table name: On table, view
 Trigger Type: Row or statement
 When clause: Restricting condition
 Trigger body: PL/SQL block

“Before triggers” execute the trigger body before the triggering DML event on a
table. These are frequently used to determine whether that triggering statement should be
allowed to complete. This situation enables you to eliminate unnecessary processing of the
triggering statement and it eventual rollback in cases where an exception is raised in the
triggering action.
“After triggers” are used when the triggering statement is to be completed before
the triggering action and to perform a different action on the same triggering statement if a
BEFORE trigger is already present.
“Instead of Triggers” are used to provide a transparent way of modifying views
that cannot be modified directly through SQL DML statements because the view is not
inherently modifiable. You can write INSERT, UPDATE, and DELETE statements

55
against the view. The INSTEAD OF trigger works invisibly in the background performing
the action coded in the trigger body directly on the underlying tables.
Triggering user events:
o INSERT
o UPDATE
o DELETE
Trigger Components:

o Statement: The trigger body executes once for the triggering event. This is the
default. A statement trigger fires once, even if no rows are affected at all.
o Row: The trigger body executes once for each row affected by the triggering
event. A row trigger is not executed if the triggering event affects no rows.

Trigger Body:

The trigger body is a PL/SQL block or a call to a procedure.


Syntax:
Create or replace Trigger<Triggername> {Before,After} {Delete, Insert, Update } On
<Tablename> For Each row when Condition
Declare
<Variable declarations>;
<Constant Declarations>;
Begin
<PL/SQL> Subprogram Body;
Exception
Exception Pl/SQL block;
End;

How to Delete a Trigger:

The syntax for Deleting the Trigger is as follows:

Drop Trigger <Triggername>;

Queries and Output

sql> set serveroutput on;

PROGRAM (A):
Create a trigger which displays an error message when the employee records with
salary greater than 2000 are deleted.

SQL>create or replace trigger emptrig

56
before delete on emp
referencing old as nrow
for each row
when(nrow.salary >2000)
begin
raise_application_error(-20001,'Salary greater than 2000');
end;
/
Trigger created.

SQL> delete from emp where salary>2000;


delete from emp where salary>2000
*
ERROR at line 1:
ORA-20001: Salary greater than 2000
ORA-06512: at "IT3A23.EMPTRIG", line 2
ORA-04088: error during execution of trigger 'IT3A23.EMPTRIG'

PROGRAM (B):
Create a trigger which displays message whenever anyone attempts to change dept
table.

SQL>create or replace trigger depttrig


before update on dept
for each row
begin
dbms_output.put_line('Location being Updated from '||(:old.loc)||' to '||(:new.loc));
end;
/
Trigger created.

SQL> update dept set loc='Madurai' where deptno=10;


Location being Updated from Dindigul to Madurai

1 row updated.
PROGRAM (C):

INPUT:
EMP

EMPNO SALARY
10 0
11 1000
12 1200

SALDET

57
EMPNO DEPT TOTAL
10 11 900

SQL> create trigger triplet


after update of salary on emp for each row
begin
update saldet set total = total+:new.salary where
empno =:new.empno;
end;
/
OUTPUT:
trigger created.

SQL> update emp set salary=1000 where empno=10;


1 row updated.
EMP

EMPNO SALARY
10 1000
11 1000
12 1200
SALDET

EMPNO DEPT TOTAL


10 11 1900
PROGRAM (D):

SQL> create or replace trigger second


before update on emp for each row
begin
if :new.salary>1000 or :new.dept =10;
then raise_application_error (-20001,’You are not allowed to insert.’);
end if;
end;
/
OUTPUT:
trigger created.

SQL> update emp set salary =1200 where dept =10;


Error at line 1:
ORA -20001: You are not allowed to insert.

RESULT:
Thus triggers were implemented successfully.

58
Exp.No:10 DATABASE DESIGN USING ER MODELING,
Date: NORMALIZATION

AIM:
To implement any application using ER model and normalization.
ER diagram:
Chen Notation

 ORDER (OrderNum (key), OrderDate, SalesPerson)


 ORDERITEMS (OrderNum (key)(fk) , ItemNum (key), PartNum, Quantity, Cost)
 In the above example, in the ORDERITEMS Relation: OrderNum is the
Foreign Key and OrderNum plus ItemNum is the Composite Key.

Chen Notation

In the ORDER Relation: OrderNum is the Key.

Representing Relationships

 1:1 Relationships. The key of one relation is stored in the second relation. Look at
example queries to determine which key is queried most often.
 1:N Relationships.
Parent - Relation on the "1" side.
Child - Relation on the "Many" side.
 Represent each Entity as a relation.

59
Copy the key of the parent into the child relation.
 CUSTOMER (CustomerID (key), Name, Address, ...)
 ORDER (OrderNum (key), OrderDate, SalesPerson, CustomerID (fk))

 M:N Relationships. Many to Many relationships cannot be directly implemented


in relations.
 Solution: Introduce a third Intersection relation and copy keys from original
two relations.

Chen Notation

 SUPPLIER (SupplierID (key), FirmName, Address,


...) COMPONENT (CompID (key), Description, ...)
SUPPLIER_COMPONENT (SupplierID (key),
CompID (key))
 Note that this can also be shown in the ER diagram. Also, look for
potential added attributes in the intersection relation.

RESULT:
Thus the ER Database design using E-R model and Normalization was
implemented successfully.

60
Exp.No:11
DESIGN AND IMPLEMENTATION OF BANKING SYSTEM.
Date:

AIM:
To design and implement banking system using visual basic 6.0.

Connectivity:
i. Open the VB 6.0 in standard exe form and right circle in the tool box select components.
ii. Select MS ADO data control 6.0 (SP4) OLEDB in component list.
iii. Right click over ADODC control and select the properties.
iv. Select MSOLE DB provides for ODBC drivers in provider..

Algorithm:
1. Place all the controls in the form as shown.
2. To place the ADO controls do the following procedure.
3. Go to project Component.
4. Select the checkbox showing “MICROSOFT ADO DATA CONTROL”and Press
apply close.
5. Place the ADO control on the form.
6. Create a table in SQL plus and insert some values in it.
7. Now type the command ‘commit;’ and return back to VB.
8. Select the ADO control and click the right mouse select ADODC properties.
9. A dialog box will appear, press the build button. Select ‘Microsoft OLEDB
provider for oracle” press next button”.
10. In the connection tab, give the server name, user name and password.
11. Press the” TEST CONNECTION” button. A message box will appear if the steps
were followed correctly. Press OK button.
12. Select authentication tab. Give the username and password again. Select record
source tab. In the table or stored procedure name control box, select the name and give
OK.
13. Now select the text buttons one by one and in the properties window set the data
sources combo box to point to ADODC1.select the corresponding fields of the text box in
the data fields combo box
14. Write the coding for command buttons and run the form.

61
Data report :
1. Go to Project->Components->Designers->Data Report,Data Environment and click
Apply,then OK.

2. In Project Explorer - > Form1->Right Click-> Add->Data Environment, Data Report.

3. In Data Environment1, Right Click on Connection1->Properties->Provider->


Microsoft OLE DB provider for Oracle -> Next-> Server-orcl, User-itc48,Password-itc
Test Connection->Test Connection Succeeded->OK->OK

4. In Data Environment1,
Right Click on Connection1->Add Command-> Command1

5. In Command1, Right Click->Properties-> Database Object-Table, Object Name –


ITB67.BANK - > Apply, then OK

6. Drag Command1 into Detail Section of Data Report1 and Make Alignments

7. In Property Window of DataReport1, change Data Source-Data Environment1


Data Member-Command1.

Database Schema:

Name Null? Type


----------------------------------------- -------- ----------------------------
NAME VARCHAR2(25)
PASS VARCHAR2(26)
ACCNO NUMBER(25)
ACTYPE VARCHAR2(25)
ADDR VARCHAR2(25)
AMT NUMBER(25)

FORM DESIGN:
Form1

62
Dim con As New ADODB.Connection
Dim rec As New ADODB.Recordset
Private Sub Command1_Click()
Form3.Show
End Sub

Private Sub Command3_Click()


Unload Me
End Sub

Private Sub Form_Load()


con.Open "Provider=MSDAORA.1;Password=itb;User ID=itb11;Data
Source=orcl;Persist Security Info=True"
rec.Open "select * from DET1", con, adOpenDynamic
MsgBox ("successfully connected")
End Sub

Private Sub ok_Click()


Do While Not rec.EOF
If rec.Fields(0) = Text1.Text And rec.Fields(1) = Text2.Text Then
If rec.Fields(2) = Text3.Text Then
Unload Me
Form1.Show
Exit Sub
End If
MsgBox "Accout no is not correct", vbCritical
End If
rec.MoveNext
Loop
MsgBox "user name or password is not correct", vbCritical
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text1.SetFocus
End Sub

63
Form2

Dim con As New ADODB.Connection


Dim rec As New ADODB.Recordset
Dim con1 As New ADODB.Connection
Dim rec1 As New ADODB.Recordset

Private Sub accept_Click()


If Combo2.Text = "deposit" Then
Label10.Caption = Val(Label10.Caption) + Val(Text6.Text)
con.Execute "update det1 set amt='" & Label10.Caption & "' where accno='" &
Combo1.Text & "'"
MsgBox ("sucessfully updated")
Else
If Combo2.Text = "transaction" Then

64
Form4.Show
Else
If Val(Label10.Caption) >= 501 Then
If Val(Label10.Caption) - Val(Text6.Text) >= 500 Then
Label10.Caption = Val(Label10.Caption) - Val(Text6.Text)
con.Execute "update det1 set amt='" & Label10.Caption & "' where accno='" &
Combo1.Text & "'"
MsgBox ("sucessfully debited")
Else
MsgBox "min amt is 500", vbCritical, "below 500"
End If
Else
MsgBox "min amt is 500", vbCritical, "below 500"
End If
End If
End If
accept.Enabled = False
End Sub

Private Sub cmdtrans_Click()


fratrans.Visible = Not fratrans.Visible
End Sub

Private Sub cmdview_Click()


fraview.Visible = Not fraview.Visible
rec.MoveFirst
Text1.Text = rec.Fields(0)
Text2.Text = rec.Fields(2)
Text3.Text = rec.Fields(4)
Text4.Text = rec.Fields(3)
Text5.Text = rec.Fields(5)
End Sub

Private Sub Combo1_Click()


rec.MoveFirst
Do While (rec.EOF = False)
If (StrComp(rec.Fields(2), Combo1.Text) = 0) Then
Label10.Caption = rec.Fields(5)
End If
rec.MoveNext
Loop
accept.Enabled = True
End Sub

Private Sub showrec()


Text1.Text = rec.Fields(0)

65
Text2.Text = rec.Fields(2)
Text3.Text = rec.Fields(4)
Text4.Text = rec.Fields(3)
Text5.Text = rec.Fields(5)
End Sub

Private Sub Command1_Click()


con1.Open "Provider=MSDAORA.1;Password=itb;User ID=itb11;Data
Source=orcl;Persist Security Info=True"
rec1.Open "select * from DET1 where amt>20000", con1, adOpenDynamic
con1.Execute "select * from DET1 where amt>20000"
MsgBox ("successfully generated")
DataReport1.Show
End Sub

Private Sub first_Click()


rec.MoveFirst
showrec
End Sub

Private Sub Form_Load()


con.Open "Provider=MSDAORA.1;Password=itb;User ID=itb11;Data
Source=orcl;Persist Security Info=True"
rec.Open "select * from DET1", con, adOpenDynamic
MsgBox ("successfully connectted")
rec.MoveFirst
Do While Not rec.EOF
Combo1.AddItem rec.Fields(2)
rec.MoveNext
Loop
Combo2.AddItem "deposit"
Combo2.AddItem "withdraw"
Combo2.AddItem "transaction"
fraview.Visible = False
fratrans.Visible = False
End Sub

Private Sub last_Click()


rec.MoveLast
showrec
End Sub

Private Sub next_Click()


rec.MoveNext
If rec.EOF = True Then
MsgBox "last record", vbCritical

66
rec.MoveLast
End If
showrec
End Sub

Private Sub previous_Click()


rec.MovePrevious
If rec.BOF = True Then
MsgBox "first record", vbCritical
rec.MoveFirst
End If
showrec
End Sub

Private Sub clear()


Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
End Sub

Form3

Dim con As New ADODB.Connection


Dim rec As New ADODB.Recordset
Private Sub Add_Click()

67
con.Execute "insert into det1 values('" & Text1.Text & "','" & Text2.Text & "','" &
Val(Text3.Text) & "','" & Text4.Text & "','" & Text5.Text & "','" & Val(Text6.Text) &
"')"
MsgBox "record updated", vbInformation, "ok"
Unload Me
End Sub

Private Sub Cancel_Click()


Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
rec.AddNew
End Sub

Private Sub Form_Activate()


Text1.SetFocus
End Sub
Private Sub Form_Load()
con.Open "Provider=MSDAORA.1;Password=itb;User ID=itb11;Data
Source=orcl;Persist Security Info=True"
rec.Open "select * from DET1", con, adOpenDynamic
MsgBox ("successfully connectted")
End Sub

68
DataReport

RESULT:
Thus the Banking system was successfully designed using VB6.0 and ORACLE.

69

You might also like