Вы находитесь на странице: 1из 38

Sahrdaya College of Engineering and Technology 1

Departmental Vision

To evolve as a national level center of excellence in academics and research with the aim of
imparting contemporary knowledge in the field of Computer Science and Engineering.

2. Departmental Mission

1. Have state of art infrastructure and resources for teaching and research.
2. Impart relevant technical knowledge,skills and attributes along with values and ethics.
3. Enhance research quality and creativity through innovative teaching learning
methodologies.
4. Mold Computer Science Engineering Professionals in synchronization with the dynamic
industry requirements, worldwide.
5. Inculcate essential leadership qualities coupled with commitment to the society.

3. Programme Educational Objectives (PEOs)

Take up challenging careers in suitable corporate, business or educational


PEO1
sectors across the world, in multi-cultural work environment.

Continuously strive for higher achievements in life keeping moral and ethical
PEO2
values such as honesty, loyalty, good relationship and best performance, aloft.

Be knowledgeable and responsible citizens with good team-work skills,


PEO3
competent leadership qualities and holistic values.

Sahrdaya College of Engineering and Technology 2


Subject Name: CS 333 Application Software Development Lab
Department of Students: CSE
Semester: V

Prepared By Approved By

Livya George and Anusree Dr. Vince Paul


Asst. Professor HOD
CSE Dept. CSE Dept.

Sahrdaya College of Engineering and Technology 3


Sahrdaya College of Engineering and Technology 4
Sahrdaya College of Engineering and Technology 5
EXPERIMENT LIST

Exp.
Experiment Name Page No.
No.

1 Creating relationship between the databases. 7

2 Creating a database to set various constraints. 11

3 Creation of Views and Assertions 15

4 Implementation of Build in functions in RDBMS 17

5 Implementation of various aggregate functions in SQL 21

6 Implementation of Order By, Group By & Having clause. 23

7 Implementation of set operators, nested queries and Join queries 25

8 Implementation of various control structures using PL/SQL 27

9 Creation of Procedures and Functions 28

10 Creation of Packages 34

11 Creation of database Triggers and Cursors 36

Mini project (Application Development using Oracle/ MySQL using


12 38
Database Connectivity)

Sahrdaya College of Engineering and Technology 6


EXPERIMENT # 1
CREATING RELATIONSHIP BETWEEN THE DATABASES
Aim:
To create databases and implement the relationship between databases using join
operation.
Theory:
JOINS:
Joins are used to retrieve the data from multiple tables.
Types of Joins:
1. EQUI_JOIN
2. NON EQUI_JOIN
3. SELF JOIN
4. OUTER JOIN
4.1 Right outer join
4.2 Left outer join
4.3 Full outer join
 INNER JOIN/ NATURAL JOIN/ JOIN: It is a binary operation that allows us to combine
certain selections and a Cartesian product into one operation.
 OUTER JOIN: It is an extension of join operation to deal with missing information.
 Left Outer Join: It takes 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 natural join.
 Right Outer Join: It takes tuples in the right relation that did not match with any tuple in
the left relation, pads the tuples with null values for all other attributes from the left relation and
adds them to the result of the natural join.
 Full Outer Join: It combines tuples from both the left and the right relation and pads the
tuples with null values for the missing attributes and hem to the result of the natural join.
CREATING TABLES FOR DOING JOIN AND NESTED QUERY OPERATIONS
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create two different tables with its essential attributes.
STEP 3: Insert attribute values into the table.
STEP 4: Create the table object for easy reference.
STEP 5: Join two tables by using JOIN operator.
STEP 6: Display the result of the result table.
STEP 7: Stop the program.
Creating Dept table:
SQL> create table dept(dno number(10),dname varchar(10),loc varchar(10));
Table created.
SQL> insert into dept values(10,'inventory','hyd');
1 row created.
SQL> insert into dept values(20,'finance','bglr');
1 row created.

SQL> insert into dept values(30,'HR','mumbai');


1 row created.
SQL> select * from dept;
DNO DNAME LOC
---------- ---------- ----------

Sahrdaya College of Engineering and Technology 7


10 inventory hyd
20 finance bglr
30 HR mumbai
Creating emp2 table:
SQL> create table emp2(eno number(10),ename varchar(10),job varchar(10),M
er(10),dno number(10));
Table created.
SQL> insert into emp2 values(111,'saketh','analyst',444,10);
1 row created.
SQL> insert into emp2 values(222,'sandeep','clerk',333,20);
1 row created.
SQL> insert into emp2 values(333,'jagan','manager',111,10);
1 row created.
SQL> insert into emp2 values(444,'madhu','engineer',222,40);
1 row created.
SQL> select * from emp2;
ENO ENAME JOB MGR DNO
---------- ---------- ---------- ---------- ----------
111 saketh analyst 444 10
222 sandeep clerk 333 20
333 jagan manager 111 10
444 madhu engineer 222 40
1. Equijoin:
A join which contains an equal to ‘=’ operator in this joins condition
SQL> select eno,ename,job,dname,loc from emp2 e,dept d where e.dno=d.dno;
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
333 jagan manager inventory hyd
Using Clause:
SQL> select eno,ename,job,dname,loc from emp2 e join dept d using(dno);
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
333 jagan manager inventory hyd
On Clause:
SQL> select eno,ename,job,dname,loc from emp2 e join dept d on(e.dno=d.dno);
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
333 jagan manager inventory hyd
2. Non-Equijoin:
A join which contains an operator other than equal to ‘=’ in the join condition.
SQL> select eno,ename,job,dname,loc from emp2 e,dept d where e.dno>d.dno;
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------

Sahrdaya College of Engineering and Technology 8


222 sandeep clerk inventory hyd
444 madhu engineer inventory hyd
444 madhu engineer finance bglr
444 madhu engineer HR Mumbai
3. Self Join:
Joining the table itself is called self join.
SQL> select e1.eno,e2.ename,e1.job,e2.dno from emp2 e1,emp2 e2 where e1.eno=e2
gr;
ENO ENAME JOB DNO
---------- ---------- ---------- ----------
444 saketh engineer 10
333 sandeep manager 20
111 jagan analyst 10
222 madhu clerk 40
4. Natural Join:
It compares all the common columns.
SQL> select eno,ename,job,dname,loc from emp2 natural join dept;
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
333 jagan manager inventory hyd
5. Cross Join:
This will give the cross product.
SQL> select eno,ename,job,dname,loc from emp2 cross join dept;
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
111 saketh analyst inventory hyd
222 sandeep clerk inventory hyd
333 jagan manager inventory hyd
444 madhu engineer inventory hyd
111 saketh analyst finance bglr
222 sandeep clerk finance bglr
333 jagan manager finance bglr
444 madhu engineer finance bglr
111 saketh analyst HR mumbai
222 sandeep clerk HR mumbai
333 jagan manager HR mumbai
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
444 madhu engineer HR mumbai
12 rows selected.
6. Outer Join:
It gives the non matching records along with matching records.
6.1 Left Outer Join:
This will display the all matching records and the records which are in left hand side table those
that are in right hand side table.
SQL> select eno,ename,job,dname,loc from emp2 e left outer join dept d on(e.dno=
d.dno); (OR)

Sahrdaya College of Engineering and Technology 9


SQL> select eno,ename,job,dname,loc from emp2 e,dept d where e.dno=d.dno(+);
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
333 jagan manager inventory hyd
111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
444 madhu engineer
6.2 Right Outer Join:
This will display the all matching records and the records which are in right hand side table those
that are not in left hand side table.
SQL> select eno,ename,job,dname,loc from emp2 e right outer join dept d on(e.dno =d.dno);
(OR)
SQL> select eno,ename,job,dname,loc from emp2 e,dept d where e.dno(+)=d.dno;
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
333 jagan manager inventory hyd
HR mumbai
6.3 Full Outer Join:
This will display the all matching records and the non matching records from both tables.
SQL> select eno,ename,job,dname,loc from emp2 e full outer join dept d on(e.dno=
d.dno);
ENO ENAME JOB DNAME LOC
---------- ---------- ---------- ---------- ----------
333 jagan manager inventory hyd
111 saketh analyst inventory hyd
222 sandeep clerk finance bglr
444 madhu engineer
HR Mumbai

Expected Outcome
Studied the relationship between databases and has been implemented using join operation.

Sahrdaya College of Engineering and Technology 10


EXPERIMENT #2
CREATING A DATABASE TO SET VARIOUS CONSTRAINTS.
Aim:
To create a database using the following constraints
*Not Null
*Unique
*Primary Key
*Foreign Key
*Check
*Default
Theory
1. NOT NULL CONSTRAINT:
Syntax: create table table_name(column1 data type not null,column2 data type,…);
Description: To enforce a field to always contain a value.

SQL> desc student


Name Null? Type
------------------------------- -------- -------------------------------
SNO NUMBER
REGNO NOT NULL NUMBER
NAME VARCHAR2(20)
2. UNIQUE CONSTRAINT:
The unique constraint uniquely identifies each record in a database table.
a) Unique constraint on create table
Syntax: create table table_name(column1 data type unique,column2 data
type,…);
Description:To uniquely identify each record in a database.
Output: Table created.
b) Unique constraint on alter table
Syntax: Alter table table_name add unique(column name);
Description:To create a unique constraint on a column when the table is
alredy created
SQL> alter table student add unique(sno);
Output: Table altered.
c) Unique constraint on multiple column
Syntax: alter table table_name add unique(column 1,column2,..);
Description:To add unique constraint on multiple column.
SQL> alter table student add unique(sno,address);
Output: Table altered.
d) To drop unique constraint
Syntax: alter table table_name drop unique(column name);
Description:To drop the unique constraint of the table.
SQL> alter table student drop unique(sno);
Output: Table altered.
3. PRIMARY KEY CONSTRAINT:
The primary key constraint uniquely identifies each records in a database table.
a) Primary key constraint on create table
Syntax: create table table_name(column_name data type primary key,…);
Description:To create a primary constraint while creating a table.

Sahrdaya College of Engineering and Technology 11


Output: Table created.
SQL>desc student;
Name Null? Type
--------------------------------- -------- -------------------------
SNO NOT NULL NUMBER
REGNO NUMBER
NAME VARCHAR2(20)
Inserting non unique value:
SQL>select *from student;
SNO REGNO NAME
-------- ----------- ---------------
1 8001 arun
2 8002 sasi
SQL> insert into students values(2,8004,'sasi');
Output:
insert into students values(2,8004,'sasi')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C003010) violated
Inserting null value:
SQL>insert into students(regno,name)values(8002,'abi');
Output:
insert into students(regno,name)values(8002,'abi')
*
ERROR at line 1:
ORA-01400:cannot insert NULL into ("SCOTT"."STUDENTS"."SNO")
b) Primary key constraint on alter table
Syntax: alter table table_name add primary key(column name);
Description:To add a primary key after creating a table.
SQL> alter table student add primary key(sno);
Output: Table altered.
c) To drop primary key constraint
Syntax: alter table table_name drop primary key;
Description:To drop the primary key of the table
SQL>alter table student drop primary key;
Output: Table altered.
SQL> desc student;
Name Null? Type
---------------------------------- -------- -------------------------
SNO NUMBER
REGNO NUMBER
NAME VARCHAR2(20)
4. FOREIGN KEY CONSTRAINT:
A foreign key in one table points to a primary key in another table.
a) Foreign key constraint on create table
Syntax: create table table_name2(column1 data type,column2 data type,
foreign key(column name)references table_name1(column name));
Description:To add foreign key constraint on creatingba table.
Output: Table created.

Sahrdaya College of Engineering and Technology 12


b) Foreign key constraint on alter table
Syntax: alter table table_name2 add foreign key references table_name2
(column name);
Description:To add foreign key constraint after creating table.
Output: Table altered.
5. CHECK CONSTRAINT:
The check constraint is used to limit the value range that can be placed in a column.
a) Check constraint on create table
Syntax: create table table_name(column1 data type,column2 data
type,…check(condition));
Description: To add the check constraint while creating a table.
Output: Table created.
Inserting values less than 0:
Output:
insert into person values(-1,'abi','tirupur')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.SYS_C003034) violated
b) Check constraint on alter table
Syntax: alter table table_name add check(condition);
Description:To add the check constraint after creating the table.
Output: Table altered.
6. DEFAULT CONSTRAINT:
The default constraint is used to insert a default value into a column.
a) Default constraint on create table
Syntax: create table table_name(column1 data type,column2 data
type default value);
Description:To insert a default values in a particular field while creating
table.
Output: Table created.
Inserting default values:
SQL> select *from person;
PID NAME ADDRESS CITY
---------- -------------------- -------------------- ---------------
1001 kumar gandhi nagar tirupur
b) Default constraint on alter table
Syntax: alter table table_name add column_name data type default value;
Description:To insert the default value in particular field using alter.
Output: Table altered.
SQL> select *from person;
PID NAME ADDRESS CITY JOB
---------- -------------- ----------------- ------------ ---------------
1001 kumar gandhi nagar tirupur programmer
1002 sasi raja nagar tirupur programmer
ALGORITHM:
Step 1: Start.
Step 2: Go to SQL.
Step 3: Enter the user name and password.
Step 4: Type the commands for various constraints to perform various operations on

Sahrdaya College of Engineering and Technology 13


the tables.
Step 5: The output is displayed.
Step 6: Stop.
Expected Outcome
Thus the Creation of a database to set various constraints has been implemented.

Viva Questions:
1. Define the “integrity Rules”
2. Discuss About the following
• Primary Key
• Candidate Key
• Foreign Key
• Secondary Key
3. What is meant by Constraints?
4. Define UID?
5. Explain about the following integrity with example
• Entity Integrity
• Domain Integrity
• Referential Integrity
• Column Integrity
6. Write the syntax for Check Constraints and Null constraints.
7. What is meant by Alternate key?
8. What are four functions that an ALTER statement can perform on constraints?
9. Why might you want to disable and then re-enable a constraint?
10. What are the restrictions on defining a CHECK constraint?
11. What are the limitations of constraints that may be applied at the column level and at the
table level?
12. Why is it important to give meaningful names to constraints?

Sahrdaya College of Engineering and Technology 14


EXPERIMENT # 3
CREATION OF VIEWS AND ASSERTIONS
Aim:
To write a simple SQL commands for creating view.
Theory
1. CREATE VIEW:
Syntax: create view view_name as select column_name(s) from table_name
where condition;
Description: To create a view from the table or another view.
Output: View created.
To view the view
Syntax: select *from view_name;
Description: To view the view that is created.
Output:
REGNO NAME
---------- --------------------
8001 arun
8003 kalai
8004 kumar
8005 sasi
2. UPDATE VIEW:
Syntax: create or replace view view_name as select column_name(s) from
table name where condition;
Description: To update the view that is already created.
Output: View created.
SQL> select *from stud1;
SNO REGNO NAME
---------- ---------- --------------------
1 8001 arun
3 8003 kalai
4 8004 kumar
5 8005 sasi
3. DROP VIEW:
Syntax: drop view view_name;
Description:To drop the view that is created.
Output: View dropped.
Algorithm:
Step 1: Start.
Step 2: Go to SQL.
Step 3: Enter the user name and password.
Step 4: Type the commands for creating,updating and droping views
Step 5: The output is displayed.
Step 6: Stop.
Expected Outcome
Thus the relationship between databases has been implemented using join operation.
Viva Queations:
1. Define Views.
2. Write a syntax for creating Views.
3. List out the uses of creating Views.

Sahrdaya College of Engineering and Technology 15


4. How to create a View alias.
5. Write the syntax for UPDATE AND DROP VIEW.
6. How do you communicate with an RDBMS?
7. Define SQL and state the differences between SQL and other conventional programming
Languages.
8. What are the restrictions on modifying data through a view?

Sahrdaya College of Engineering and Technology 16


EXPERIMENT # 4
IMPLEMENTATION OF BUILD IN FUNCTIONS IN RDBMS
Aim:
To understand and implement various types of function in SQL.
Theory
Conversion Functions
String Functions
Date Functions
Mathematical Functions
Group Functions
Miscellaneous Functions

DATE FUNCTION

1. Add_month
This function returns a date after adding a specified date with specified number of months.
Syntax: Add_months(d,n); where d-date n-number of months
Example: Select add_months(sysdate,2) from dual;
2. last_day
It displays the last date of that month.
Syntax: last_day (d); where d-date
Example: Select last_day (‘1-jun-2009’) from dual;
3. Months_between
It gives the difference in number of months between d1 & d2.
Syntax: month_between (d1,d2); where d1 & d2 -dates
Example: Select month_between (‘1-jun-2009’,’1-aug-2009’) from dual;
4. next_day
It returns a day followed the specified date.
Syntax: next_day (d,day);
Example: Select next_day (sysdate,’wednesday’) from dual
5. round
This function returns the date, which is rounded to the unit specified by the format model.
Syntax : round (d,[fmt]);
where d- date, [fmt] – optional. By default date will be rounded to the nearest day
Example: Select round (to_date(‘1-jun-2009’,’dd-mm-yy’),’year’) from dual;
Select round (‘1-jun-2009’,’year’) from dual;

NUMERICAL FUNCTIONS

Command Query Output

Abs(n) Select abs(-15) from dual; 15

Ceil(n) Select ceil(55.67) from dual; 56

Exp(n) Select exp(4) from dual; 54.59

Floor(n) Select floor(100.2) from dual; 100

Sahrdaya College of Engineering and Technology 17


Power(m,n) Select power(4,2) from dual; 16

Mod(m,n) Select mod(10,3) from dual; 1

Round(m,n) Select round(100.256,2) from dual; 100.26

Trunc(m,n) Select trunc(100.256,2) from dual; 100.23

Sqrt(m,n) Select sqrt(16) from dual; 4

CHARACTER FUNCTIONS

Command Query Output

initcap(char); select initcap(“hello”) from dual; Hello

lower (char); select lower (‘HELLO’) from dual; hello

upper (char); select upper (‘hello’) from dual; HELLO

ltrim (char,[set]); select ltrim (‘cseit’, ‘cse’) from dual; select it

rtrim (char,[set]); rtrim (‘cseit’, ‘it’) from dual; cse

replace (char,search string, replace select replace(‘jack and jue’,‘j’,‘bl’) from black and
string); dual; blue

substr (char,m,n); select substr (‘information’, 3, 4) from dual; Form

CONVERSION FUNCTION

1. to_char()
Syntax: to_char(d,[format]);
This function converts date to a value of varchar type in a form specified by date format.
If format is negelected then it converts date to varchar2 in the default date format.
Example: select to_char (sysdate, ’dd-mm-yy’) from dual;
2. to_date()
Syntax: to_date(d,[format]);
This function converts character to date data format specified in the form character.
Example: select to_date(‘aug 15 2009’,’mm-dd-yy’) from dual;

MISCELLANEOUS FUNCTIONS

Sahrdaya College of Engineering and Technology 18


1. uid – This function returns the integer value (id) corresponding to the user currently
logged in.
Example: select uid from dual;
2. user – This function returns the logins user name.
Example: select user from dual;
3. nvl – The null value function is mainly used in the case where we want to consider null values
as zero.
Syntax; nvl(exp1, exp2)
If exp1 is null, return exp2. If exp1 is not null, return exp1.
Example: select custid, shipdate, nvl(total,0) from order;
4. vsize: It returns the number of bytes in expression.
Example: select vsize(‘tech’) from dual;

GROUP FUNCTIONS

A group function returns a result based on group of rows.


1. avg - Example: select avg (total) from student;
2. max - Example: select max (percentagel) from student;
2.min - Example: select min (marksl) from student;
4. sum - Example: select sum(price) from product;

COUNT FUNCTION

In order to count the number of rows, count function is used.


1. count(*) – It counts all, inclusive of duplicates and nulls.
Example: select count(*) from student;
2. count(col_name)– It avoids null value.
Example: select count(total) from order;
2. count(distinct col_name) – It avoids the repeated and null values.
Example: select count(distinct ordid) from order;

Viva Questions And Answers

1. Define function?
Function is a group of code that accepts zero or more arguments and both return one
or more results. Both are used to manipulate individual data items.
2. Write the two types of functions
i. Single row functions
ii. Group functions
3. What are single row functions?
A single row function or scalar function returns only one value for every row
queries in table. Single row function can appear in a select command and can also be
included in a where clause. The single row function can be broadly classified as,
o Date Function o Numeric Function
o Character Function o Conversion Function
o Miscellaneous Function
4. List some character funcitons
initcap(char);
lower (char);

Sahrdaya College of Engineering and Technology 19


upper (char);
ltrim (char,[set]); rtrim (char,[set]);

Algorithm:
Step 1: Start.
Step 2: Go to SQL.
Step 3: Enter the user name and password.
Step 4: Type the commands for creating table and perform Build in functions on
the tables.
Step 5: The output is displayed.
Step 6: Stop.

Expected Outcome
Studied and Implemented of Built in functions in RDBMS

Sahrdaya College of Engineering and Technology 20


EXPERIMENT #5.
IMPLEMENTATION OF VARIOUS AGGREGATE FUNCTIONS IN SQL
Aim:
To perform aggregation of data using group functions, grouping data using group
function, exclude or include the group by having clause using SQL commands.
Algorithm:
Step 1: Start.
Step 2: Go to SQL.
Step 3: Enter the user name and password.
Step 4: Type the commands for creating a table and perform aggregation of data using
group functions.
Step 5: The output is displayed.
Step 6: Stop.
Theory
Group function operates on set of rows to give one result per group.
i) Group functions:
Each function accepts an argument.
Types of group function:
1. AVG(n): To average value of n, ignoring null values
2. a) count(exp): It returns number of count
b) count(*): It returns number of counts without ignoring null values and duplicate values
3. MAX(exp): It returns the maximum value of expression and it ignores null values.
4. MIN(exp): It returns the minimum value of expression and it ignores null values.
5. STDDEV(n): It returns standard deviation of n and it ignores null values.
6. SUM(n): It return sum of n, and it ignores null values.
7. VARIANCE(n): It returns variance of n and it ignores null values.

Aggregative operators: In addition to simply retrieving data, we often want to perform some
computation or summarization. SQL allows the use of arithmetic expressions. We now consider a
powerful class of constructs for computing aggregate values such as MIN and SUM.
1. Count: COUNT following by a column name returns the count of tuple in that column. If
DISTINCT keyword is used then it will return only the count of unique tuple in the column.
Otherwise, it will return count of all the tuples (including duplicates) count (*) indicates all the
tuples of the column.
Syntax: COUNT (Column name)
Example: SELECT COUNT (Sal) FROM emp;
2. SUM: SUM followed by a column name returns the sum of all the values in that column.
Syntax: SUM (Column name)
Example: SELECT SUM (Sal) From emp;
3. AVG: AVG followed by a column name returns the average value of that column values.
Syntax: AVG (n1,n2..)
Example: Select AVG(10, 15, 30) FROM DUAL;
4. MAX: MAX followed by a column name returns the maximum value of that column.
Syntax: MAX (Column name)
Example: SELECT MAX (Sal) FROM emp;
SQL> select deptno,max(sal) from emp group by deptno;
DEPTNO MAX(SAL)
------ --------
10 5000

Sahrdaya College of Engineering and Technology 21


20 3000
30 2850
SQL> select deptno,max(sal) from emp group by deptno having max(sal)<3000;
DEPTNO MAX(SAL)
----- --------
30 2850
5. MIN: MIN followed by column name returns the minimum value of that column.
Syntax: MIN (Column name)
Example: SELECT MIN (Sal) FROM emp;
SQL>select deptno,min(sal) from emp group by deptno having min(sal)>1000;
DEPTNO MIN(SAL)
----- --------
10 1300
Expected Outcome
Studied and implemented various aggregate functions in SQL .

Sahrdaya College of Engineering and Technology 22


EXPERIMENT # 6.
IMPLEMENTATION OF ORDER BY, GROUP BY& HAVING CLAUSE.
AIM:
Study and Implementation of Group by , Having Clause and Order by Clause

ALGORITHM:
Step 1: Start.
Step 2: Go to SQL.
Step 3: Enter the user name and password.
STEP 2: Create a table with its essential attributes.
Step 4: Type the commands for implementing Group by, Having Clause and Order by
Clause
Step 5: The output is displayed.
Step 6: Stop.

Theory

 GROUP BY:
This query is used to group to all the records in a relation together for each
and every value of a specific key(s) and then display them for a selected set of fields the
relation.

Syntax: SELECT <set of fields> FROM <relation_name>


GROUP BY <field_name>;

Example: SQL> SELECT EMPNO, SUM (SALARY) FROM EMP GROUP BY


EMPNO;

GROUP BY-HAVING :
The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions. The HAVING clause must follow the
GROUP BY clause in a query and must also precede the ORDER BY clause if used.

Syntax: SELECT column_name, aggregate_function(column_name) FROM table_name


WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Example : SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders


FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID) GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 10;

JOIN using GROUP BY:


This query is used to display a set of fields from two relations by
matching a common field in them and also group the corresponding records for each and
every value of a specified key(s) while displaying.

Sahrdaya College of Engineering and Technology 23


Syntax: SELECT <set of fields (from both relations)> FROM relation_1,relation_2
WHERE relation_1.field_x=relation_2.field_y GROUP BY field_z;

Example:
SQL> SELECT empno,SUM(SALARY) FROM emp,dept
WHERE emp.deptno =20 GROUP BY empno;

 ORDER BY:

This query is used to display a selected set of fields from a relation in an


ordered manner base on some field.

Syntax: SELECT <set of fields> FROM <relation_name>


ORDER BY <field_name>;

Example: SQL> SELECT empno, ename, job FROM emp ORDER BY job;

JOIN using ORDER BY:


This query is used to display a set of fields from two relations by
matching a common field in them in an ordered manner based on some fields.

Syntax: SELECT <set of fields (from both relations)> FROM relation_1, relation_2
WHERE relation_1.field_x = relation_2.field_y ORDER BY field_z;

Example: SQL> SELECT empno,ename,job,dname FROM emp,dept


WHERE emp.deptno = 20 ORDER BY job;
Expected Outcome
studied and implementated of Order By, Group By& Having clause.

Sahrdaya College of Engineering and Technology 24


EXPERIMENT # 7
IMPLEMENTATION OF SET OPERATORS, NESTED QUERIES AND JOIN QUERIES

Aim : Study and implement set operators, nested queries and Join queries
Find the queries for the following :
Q1: Display all employee names and salary whose salary is greater than minimum salary of the
company and job title starts with 'A'„.
Q2: Issue a query to find all the employees who work in the same job as Arjun.
Q3: Display all the dept numbers available with the dept and emp tables avoiding duplicates.
Q4: Display all the dept numbers available with the dept and emp tables.
Q5: Display all the dept numbers available in emp and not in dept tables and vice versa.

Theory
set operators and nested queries
A subQuery is a form of an SQL statement that appears inside another SQL statement. It also
termed as nested Query. The statement containing a subQuery called a parent statement. The rows
returned by the subQuery are used by the following statement.
It can be used by the following commands:
1. To insert records in the target table.
2. To create tables and insert records in this table.
3. To update records in the target table.
4. To create view.
5. To provide values for the condition in the WHERE , HAVING IN ,
SELECT,UPDATE, and DELETE statements.
Exam:-
Creating clientmaster table from oldclient_master, table
Create table client_master
AS SELECT * FROM oldclient_master;
Using the Union, Intersect and Minus Clause:
Union Clause:
The user can put together multiple Queries and combine their output using the union
clause . The union clause merges the output of two or more Queries into a single set of
rows and column. The final output of union clause will be
Output: = Records only in Query one + records only in Query two + A single set of
records with is common in the both Queries.
Syntax:
SELECT columnname, columname
FROM tablename 1 UNION SELECT columnname, columnname From tablename2;
Intersect Clause:
The user can put together multiple Queries and their output using the
interest clause. The final output of the interest clause will be :
Output =A single set of records which are common in both Queries
Syntax:
SELECT columnname, columnname FROM tablename 1
INTERSECT
SELECT columnname, columnname FROM tablename 2;
Minus Clause:- The user can put together multiple Queries and combine their output
= records only in Query one Syntax:
SELECT columnname, columnname FROM tablename ;

Sahrdaya College of Engineering and Technology 25


MINUS
SELECT columnname, columnname FROM tablename ;
Join queries
Joint Multiple Table (Equi Join): Some times we require to treat more than one table as
though manipulate data from all the tables as though the tables were not separate object
but one single entity. To achieve this we have to join tables.Tables are joined on column
that have dame data type and data with in tables.
The tables that have to be joined are specified in the FROM clause and the
joining attributes in the WHERE clause.
Algorithm for JOIN in SQL:
1. Cartesian product of tables (specified in the FROM clause)
2. Selection of rows that match (predicate in the WHERE clause)
3. Project column specified in the SELECT clause.
1. Cartesian product:-
Consider two table student and course
Select B.*,P.*
FROM student B, course P;
2. INNER JOIN:
Cartesian product followed by selection
Select B.*,P.*
FROM student B, Course P
WHERE B.course # P.course # ;
3. LEFT OUTER JOIN:
LEFT OUTER JOIN = Cartesian product + selection but include rows from the
left table which are unmatched pat nulls in the values of attributes belonging to th e
second table
Exam:
Select B.*,P*
FROM student B left join course p
ON B.course # P.course #;
4. RIGHT OUTER JOIN:
RIGHT OUTER JOIN = Cartesian product + selection but include rows from
right table which are unmatched
Exam:
Select B.*,P.*
From student B RIGHT JOIN course P
B.course# = P course # ;
5. FULL OUTER JOIN
Exam
Select B.*,P.*
From student B FULL JOIN course P
On B.course # = P course # ;

Expected Output
Studied and implemented set operators, nested queries and Join queries.

Sahrdaya College of Engineering and Technology 26


EXPERIMENT # 8
IMPLEMENTATION OF VARIOUS CONTROL STRUCTURES USING PL/SQL

Aim : Implementation of various control structures using PL/SQL


Q1 : Write PL/SQL block which will calculate some of two numbers and display the output?
Q2: Write a PL/SQL block which accepts employee number and increment is salary by 1000?
Q3: Write a PL/SQL block which empno and delete that row from the emp table?
Q4: PL/SQL for reversing the given stringQ3: Write a PL/SQL block which empno and delete
that row from the emp table?

Theory
PL/SQL has a variety of control structures that allow you to control the behaviour of the
block as it runs. These structures include conditional statements and loops.
If-then-
else Case
o Case with no else
o Labeled case
o Searched
case Simple loop
While loop
For loop
Goto and Labels
Conditional control in PL/SQL-
Syntax:
IF <condition> THEN
<Action>
ELSEIF<condition>
<Action>
ELSE
<Action>
ENDIF;
The WHILE LOOP:
Syntax:
WHILE <condition>
LOOP
<Action>
END LOOP;
The FOR LOOP statement:
Syntax:
FOR variable IN [REVERSE] start—end
LOOP
<Action>
END LOOP;
The GOTO statement: The goto statement allows you to change the flow of control
within a PL/SQL Block.

Expected Output
studied and implemented of various control structures using PL/SQL

Sahrdaya College of Engineering and Technology 27


EXPERIMENT # 9
CREATION OF PROCEDURES AND FUNCTIONS

Aim : Creation of Procedures and Functions


Q1 : Create a procedure to insert record
Q2 : Create a function to find factorial

Theory
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design'. A subprogram
can be invoked by another subprogram or program which is called the calling program.
A subprogram can be created −
• At the schema level
• Inside a package
• Inside a PL/SQL block
At the schema level, subprogram is a standalone subprogram. It is created with the CREATE
PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be
deleted with the DROP PROCEDURE or DROP FUNCTION statement.
A subprogram created inside a package is a packaged subprogram. It is stored in the database
and can be deleted only when the package is deleted with the DROP PACKAGE statement. We
will discuss packages in the chapter 'PL/SQL - Packages'.
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters.
PL/SQL provides two kinds of subprograms −
• Functions − These subprograms return a single value; mainly used to compute and return
a value.
• Procedures − These subprograms do not return a value directly; mainly used to perform
an action.
This chapter is going to cover important aspects of a PL/SQL procedure. We will discuss
PL/SQL function in the next chapter.
Parts of a PL/SQL Subprogram
Each PL/SQL subprogram has a name, and may also have a parameter list. Like anonymous
PL/SQL blocks, the named blocks will also have the following three parts −
S.No Parts & Description
Declarative Part
It is an optional part. However, the declarative part for a subprogram does not start with
1 the DECLARE keyword. It contains declarations of types, cursors, constants, variables,
exceptions, and nested subprograms. These items are local to the subprogram and cease to
exist when the subprogram completes execution.
Executable Part
2
This is a mandatory part and contains statements that perform the designated action.
Exception-handling
3
This is again an optional part. It contains the code that handles run-time errors.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
Sahrdaya College of Engineering and Technology 28
BEGIN
< procedure_body >
END procedure_name;
Where,
• procedure-name specifies the name of the procedure.
• [OR REPLACE] option allows the modification of an existing procedure.
• The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the parameter
that will be used to return a value outside of the procedure.
• procedure-body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the
screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Procedure created.
Executing a Standalone Procedure
A standalone procedure can be called in two ways −
• Using the EXECUTE keyword
• Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
The above call will display −
Hello World

PL/SQL procedure successfully completed.


The procedure can also be called from another PL/SQL block −
BEGIN
greetings;
END;
/
The above call will display −
Hello World

PL/SQL procedure successfully completed.


Deleting a Standalone Procedure
A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting
a procedure is −
DROP PROCEDURE procedure-name;
You can drop the greetings procedure by using the following statement −
DROP PROCEDURE greetings;
Parameter Modes in PL/SQL Subprograms

Sahrdaya College of Engineering and Technology 29


The following table lists out the parameter modes in PL/SQL subprograms −
S.No Parameter Mode & Description
IN
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter.
Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a value.
1 You can pass a constant, literal, initialized variable, or expression as an IN parameter.
You can also initialize it to a default value; however, in that case, it is omitted from the
subprogram call. It is the default mode of parameter passing. Parameters are passed
by reference.
OUT
An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT
2
parameter acts like a variable. You can change its value and reference the value after
assigning it. The actual parameter must be variable and it is passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated
value to the caller. It can be assigned a value and the value can be read.
3
The actual parameter corresponding to an IN OUT formal parameter must be a variable,
not a constant or an expression. Formal parameter must be assigned a value. Actual
parameter is passed by value.
IN & OUT Mode Example 1
This program finds the minimum of two values. Here, the procedure takes two numbers using the
IN mode and returns their minimum using the OUT parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Minimum of (23, 45) : 23

PL/SQL procedure successfully completed.


IN & OUT Mode Example 2
This procedure computes the square of value of a passed value. This example shows how we can
use the same parameter to accept a value and then return another result.

Sahrdaya College of Engineering and Technology 30


DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Square of (23): 529

PL/SQL procedure successfully completed.


Methods for Passing Parameters
Actual parameters can be passed in three ways −
• Positional notation
• Named notation
• Mixed notation
Positional Notation
In positional notation, you can call the procedure as −
findMin(a, b, c, d);
In positional notation, the first actual parameter is substituted for the first formal parameter; the
second actual parameter is substituted for the second formal parameter, and so on. So, a is
substituted for x, b is substituted for y, c is substituted for z and d is substituted for m.
Named Notation
In named notation, the actual parameter is associated with the formal parameter using the arrow
symbol ( => ). The procedure call will be like the following −
findMin(x => a, y => b, z => c, m => d);
Mixed Notation
In mixed notation, you can mix both notations in procedure call; however, the positional notation
should precede the named notation.
The following call is legal −
findMin(a, b, c, m => d);
However, this is not legal:
findMin(x => a, b, c, d);
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,

Sahrdaya College of Engineering and Technology 31


• function-name specifies the name of the function.
• [OR REPLACE] option allows the modification of an existing function.
• The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the parameter
that will be used to return a value outside of the procedure.
• The function must contain a return statement.
• The RETURN clause specifies the data type you are going to return from the function.
• function-body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone function.
Example
The following example illustrates how to create and call a standalone function. This function
returns the total number of CUSTOMERS in the customers table.
We will use the CUSTOMERS table, which we had created in the PL/SQL Variables chapter −
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 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Function created.
Calling a Function
While creating a function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task. When a program calls a function,
the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or when the
last end statement is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name
and if the function returns a value, then you can store the returned value. Following program calls
the function totalCustomers from an anonymous block −
DECLARE
c number(2);

Sahrdaya College of Engineering and Technology 32


BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6

PL/SQL procedure successfully completed.

Expected Output
Created procedures and functions specified above.

Sahrdaya College of Engineering and Technology 33


EXPERIMENT # 10
CREATION OF PACKAGES

Aim : Creation of Packages

Theory
The package might include a set of procedures that forms an API, or a pool of type
definitions and variable declarations. The package is compiled and stored in the database, where
its contents can be shared by many applications.
A package is a schema object that groups logically related PL/SQL types, variables, and
subprograms. Packages usually have two parts, a specification (spec) and a body; sometimes the
body is unnecessary. The specification is the interface to the package. It declares the types,
variables, constants, exceptions, cursors, and subprograms that can be referenced from outside the
package. The body defines the queries for the cursors and the code for the subprograms.
You can think of the spec as an interface and of the body as a black box. You can debug,
enhance, or replace a package body without changing the package spec.
To create package specs, use the SQL statement CREATE PACKAGE. A CREATE PACKAGE
BODY statement defines the package body.
The body holds implementation details and private declarations, which are hidden from code
outside the package.
Following the declarative part of the package body is the optional initialization part,
which holds statements that initialize package variables and do any other one-time setup steps.
The AUTHID clause determines whether all the packaged subprograms execute with the
privileges of their definer (the default) or invoker, and whether their unqualified references to
schema objects are resolved in the schema of the definer or invoker.
A call spec lets you map a package subprogram to a Java method or external C function.
The call spec maps the Java or C name, parameter types, and return type to their SQL
counterparts.

The following is contained in a PL/SQL package:


• Get and Set methods for the package variables, if you want to avoid letting other
procedures read and write them directly.
• Cursor declarations with the text of SQL queries. Reusing exactly the same query text in
multiple locations is faster than retyping the same query each time with slight differences. It is
also easier to maintain if you need to change a query that is used in many places.
• Declarations for exceptions. Typically, you need to be able to reference these from
different procedures, so that you can handle exceptions within called subprograms.
• Declarations for procedures and functions that call each other. You do not need to worry
about compilation order for packaged procedures and functions, making them more convenient
than standalone stored procedures and functions when they call back and forth to each other.
• Declarations for overloaded procedures and functions. You can create multiple variations
of a procedure or function, using the same names but different sets of parameters.
• Variables that you want to remain available between procedure calls in the same session.
You can treat variables in a package like global variables.
• Type declarations for PL/SQL collection types. To pass a collection as a parameter
between stored procedures or functions, you must declare the type in a package so that both the
calling and called subprogram can refer to it.

Sahrdaya College of Engineering and Technology 34


The spec lists the package resources available to applications. All the information your
application needs to use the resources is in the spec. For example, the following declaration
shows that the function named factorial takes one argument of type INTEGER and returns a value
of type INTEGER:
FUNCTION factorial (n INTEGER) RETURN INTEGER; -- returns n!
That is all the information you need to call the function. You need not consider its underlying
implementation (whether it is iterative or recursive for example).
If a spec declares only types, constants, variables, exceptions, and call specs, the package body is
unnecessary. Only subprograms and cursors have an underlying implementation. In Example, the
package needs no body because it declares types, exceptions, and variables, but no subprograms
or cursors. Such packages let you define global variables, usable by stored procedures and
functions and triggers, that persist throughout a session.

Example 9-1 A Simple Package Specification Without a Body


CREATE PACKAGE trans_data AS -- bodiless package TYPE TimeRec IS RECORD
( minutes SMALLINT, hours SMALLINT); TYPE TransRec IS RECORD ( category
VARCHAR2(10), account INT, amount REAL, time_of TimeRec); minimum_balance
CONSTANT REAL := 10.00; number_processed INT; insufficient_funds EXCEPTION; END
trans_data; /

Referencing Package Contents


To reference the types, items, subprograms, and call specs declared within a package spec, use
dot notation:
package_name.type_name
package_name.item_name
package_name.subprogram_name

You can reference package contents from database triggers, stored subprograms, 3GL
application programs, and various Oracle tools. For example, you can call package procedures as
shown in Example 9-3.
The following example calls the hire_employee procedure from an anonymous block in a Pro*C
program. The actual parameters emp_id, emp_lname, and emp_fname are host variables.
EXEC SQL EXECUTE
BEGIN
emp_actions.hire_employee(:emp_id,:emp_lname,:emp_fname, ...);

Restrictions
You cannot reference remote packaged variables, either directly or indirectly. For
example, you cannot call the a procedure through a database link if the procedure refers to a
packaged variable.
Inside a package, you cannot reference host variables.

Expected Output

Created package mentioned above.

Sahrdaya College of Engineering and Technology 35


EXPERIMENT # 11
CREATION OF DATABASE TRIGGERS AND CURSORS

Aim : Creation of database Triggers and Cursors


Q1 : Trigger for displaying grade of the student
Q2 : Program to indicate invalid condition using trigger
Q3 : Cursor program for electricity bill calculation
Theory
Cursor– We have seen how oracle executes an SQL statement. Oracle DBA uses a work area for
its internal processing. This work area is private to SQL’s operation and is called a cursor.
The data that is stored in the cursor is called the Active Data set. The size of the cursor in
memory is the size required to hold the number of rows in the Active Data Set.
Explicit Cursor- You can explicitly declare a cursor to process the rows individually. A cursor
declared by the user is called Explicit Cursor. For Queries that return more than one row, You
must declare a cursor explicitly.
The data that is stored in the cursor is called the Active Data set. The size of the cursor in
memory is the size required to hold the number of rows in the Active
Why use an Explicit Cursor- Cursor can be used when the user wants to process data one row at a
time.
Explicit Cursor Management- The steps involved in declaring a cursor and manipulating data in
the active data set are:-
x Declare a cursor that specifies the SQL select statement that you want to process.
x Open the Cursor.
x Fetch the data from the cursor one row at a time.
x Close the cursor.
Explicit Cursor Attributes- Oracle provides certain attributes/ cursor variables to control the
execution of the cursor. Whenever any cursor(explicit or implicit) is opened and used Oracle
creates a set of four system variables via which Oracle keeps track of the ‘Current’ status of the
cursor.
x declare a cursor that specifies the SQL select statement that you want to process.
x Open the Cursor.
x Fetch the data from the cursor one row at a time.
x Close the cursor.
How to Declare the Cursor:-
The General Syntax to create any particular cursor is as follows:-
Cursor <Cursorname> is Sql Statement;
How to Open the Cursor:-
The General Syntax to Open any particular cursor is as follows:-
Open Cursorname;
Fetching a record From the Cursor:-
The fetch statement retrieves the rows from the active set to the variables one at a time.
Each time a fetch is executed. The focus of the DBA cursor advances to the next row in
the Active set.
One can make use of any loop structure(Loop-End Loop along with While,For) to fetch
the records from the cursor into variable one row at a time.
The General Syntax to Fetch the records from the cursor is as follows:-
Fetch cursorname into variable1,variable2,______
Closing a Cursor:-
The General Syntax to Close the cursor is as follows:-

Sahrdaya College of Engineering and Technology 36


Close <cursorname>;
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:-
x A Trigger can permit DML statements against a table any if they are issued,
during regular business hours or on predetermined weekdays.
x 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.
x It can be used to prevent invalid transactions.
x 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.
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.
Syntax For Creating Trigger:-
The syntax for Creating the Trigger is as follows:-
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>;
Expected Output
Created database Triggers and Cursors as mentioned above.

Sahrdaya College of Engineering and Technology 37


EXPERIMENT # 12
MINI PROJECT

Aim : Mini project (Application Development using Oracle/ MySQL using Database
Connectivity)

Expected Output

any mini project related to the following areas :

a.Inventory Control System.

b. Material Requirement Processing.

c. Hospital Management System.

d. Railway Reservation System.

e. Personal Information System.

f. Web Based User Identification System.

g. Timetable Management System.

h. Hotel Management System.

Contents of PROJECT REPORT


1. Project Title
2. Certificate
3. Acknowledgement
4. System Overview
5. -- Current system
6. -- Objectives of the proposed system
7. Advantages of the Proposed system (over current)
8. E.R.Diagram
9. -- Entities
10. -- Relationships
11. --Mapping Constraints
12. Database Schema/Table Definition
13. -- Table Name
14. -- Field Name
15. -- Datatype
16. -- Field size
17. -- Constraint (e.g. autogenerated, primary key, foreign key)
18. -- Validation (e.g. not null, default value)
19. Implementation
20. Output
21. Future Enhancements of the system
22. Bibliography

Sahrdaya College of Engineering and Technology 38

Вам также может понравиться