0% found this document useful (0 votes)
2 views

Samarth

The document contains a series of SQL queries for creating, manipulating, and retrieving data from various database tables related to a banking system, including DEPOSIT, BRANCH, CUSTOMER, BORROW, and PERSON. It covers operations such as creating tables, inserting, updating, deleting records, and using SQL functions for data retrieval and manipulation. The document is structured into practical sections focusing on different aspects of database management and SQL operations.

Uploaded by

si2005ya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Samarth

The document contains a series of SQL queries for creating, manipulating, and retrieving data from various database tables related to a banking system, including DEPOSIT, BRANCH, CUSTOMER, BORROW, and PERSON. It covers operations such as creating tables, inserting, updating, deleting records, and using SQL functions for data retrieval and manipulation. The document is structured into practical sections focusing on different aspects of database management and SQL operations.

Uploaded by

si2005ya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Krish solanki DBMS(202040302)

PRACTICAL-1
Creating and Manipulating Database objects and Applying Constraints (DDL)

1) Write a query to create the table of DEPOSIT.


QUERY:
create table DEPOSIT78(act_no number(5) PRIMARY KEY, c_name varchar2(10), b_name
varchar2(10), amount number(10,4), a_date date);

2) Write a query to create the table of BRANCH.


QUERY: create table BRANCH78(b_name varchar2(10) PRIMARY KEY, city
varchar2(10));

3) Write a query to create the table of CUSTOMER.


QUERY: create table CUSTOMER78(c_name varchar2(10) PRIMARY KEY, city
varchar2(10));

4) Write a query to create the table of BORROW.


QUERY:
create table BORROW78(loan_no number(5) PRIMARY KEY, c_name varchar2(10),
b_name varchar2(10), amount number(10,4));

12302040701085
1
Krish solanki DBMS(202040302)

5) Write a query to create table of PERSON.


QUERY:
create table PERSON78(p_id number(5) PRIMARY KEY, p_name varchar2(20), age
number(3));

6) Write a query to alter table of PERSON.


(i) Alter table by using ADD.
QUERY:
alter table PERSON ADD(salary number(10,4));

(ii) Alter table by using MODIFY.


QUERY:
alter table PERSON MODIFY(age int NOT NULL, salary number (10,4) NOTNULL);

12302040701085
2
Krish solanki DBMS(202040302)

7) Write a query to truncate table of PERSON.


QUERY:
truncate table PERSON;

8) Write a query to drop table of PERSON.


QUERY: drop table
PERSON;

12302040701085
3
Krish solanki DBMS(202040302)

PRACTICAL-2
Manipulating Data with Database Objects (DML)

1)Write a query to insert values in the table of DEPOSIT. QUERY:


insert into DEPOSIT78 values('&act_no', '&c_name', '&b_name', '&amount', '&a_date');

12302040701085
4
Krish solanki DBMS(202040302)

2) Write a query to insert values in the table of BRANCH.


QUERY:
insert into BRANCH78 values('&b_name', '&city');

12302040701085
5
Krish solanki DBMS(202040302)

3) Write a query to insert values in the table of CUSTOMER.


QUERY:
insert into CUSTOMER78 values('&c_name', '&city');

12302040701085
6
Krish solanki DBMS(202040302)

4) Write a query to insert values in the table of BORROW.


QUERY:
insert into BORROW78 values('&loan_no', '&c_name', '&b_name', '&amount');

12302040701085
7
Krish solanki DBMS(202040302)

5) Write a query to insert values in the table of PERSON.


QUERY:
insert into PERSON78 values('&p_id', '&p_name', '&age', '&salary');

12302040701085
8
Krish solanki DBMS(202040302)

6) Write a query to update values in the table of PERSON.


QUERY: update PERSON78 SET p_name = 'Jainil', age = 24 WHERE
p_id = 10002;

7) Write a query to delete values of the row in the table of PERSON.


QUERY: delete from PERSON78 WHERE
p_name = 'Jainil';

12302040701085
9
Krish solanki DBMS(202040302)

12302040701085
10
Krish solanki DBMS(202040302)

PRACTICAL-3
Retrieving, Restricting and Sorting Data (DRL) 1)
Write a query to display the details of the table of DEPOSIT.
QUERY:
Select * from DEPOSITE78;

2) Write a query to display the details of the table of BRANCH.


QUERY:
select * from BRANCH78;

3) Write a query to display the details of the table of CUSTOMER.


QUERY: select * from
CUSTOMER78;

4) Write a query to display the details of the table of BORROW.


12302040701085 11
Krish solanki DBMS(202040302)

QUERY: select * from


BORROW78;

5) Write a query to display all the account in DEPOSIT along with their account number
and Amount.
QUERY:
select acc_no, amount from DEPOSITE78;

6) Write a query to display details from BORROW where amount not equal to 50000.
QUERY: select * from BORROW78 WHERE
amount != 50000;

12302040701085 12
Krish solanki DBMS(202040302)

7) Write a query to display details from BORROW where amount is less than or equal to
100000. QUERY: select * from BORROW78 WHERE amount <= 100000;

8) Write a query to display details from BORROW where amount equals to 500000.
QUERY: select * from BORROW78 WHERE amount
= 500000;

9) Write a query to display details from BORROW where amount is less than 200000.
QUERY: select * from BORROW78 WHERE amount
< 200000;

12302040701085 13
Krish solanki DBMS(202040302)

10) Write a query to check whether the entered age of person is greater than or equal to
18 by altering the table of PERSON.
QUERY: alter table PERSON78 ADD
CHECK(age >= 18);

11) Write a query to find out the customer’s name starting with ‘P’ from the table of
CUSTOMER.
QUERY: select c_name from CUSTOMER78 where c_name
LIKE 'P%';

12) Write a query to find out the customer’s name ending with ‘a’ from the table of
CUSTOMER.
QUERY: select c_name from CUSTOMER78 where c_name
LIKE '%a';

12302040701085 14
Krish solanki DBMS(202040302)

13) Write a query to find out the customer’s name starting with ‘P’ and ending with ‘a’
from the table of CUSTOMER.
QUERY: select c_name from CUSTOMER78 where c_name
LIKE 'P%a';

14) Write a query to find out the customer’s name having substring ‘oo’ in between from
the table of CUSTOMER.
QUERY: select c_name from CUSTOMER78 where c_name
LIKE '%oo%';

15) Write a query to find out the customer’s name whose second letter is ‘o’ from the
table of CUSTOMER.
QUERY: select c_name from CUSTOMER78 where c_name
LIKE '_o%';

12302040701085 15
Krish solanki DBMS(202040302)

16) Write a query to find out the customer’s name starting with ‘P’ and having at least
three letters from the table of CUSTOMER.
QUERY: select c_name from CUSTOMER78 where c_name
LIKE 'P__%';

17) Write a query to find out the person’s name having age between 16 and 19 from the
table of PERSON.
QUERY:
select p_name from person78 where age BETWEEN 16 AND 19;

18) Write a query to find out the customer’s name who opened account between
‘18-NOV-2020’ and ‘18-NOV-2021’ from the table of DEPOSIT. QUERY:
select c_name from DEPOSITE78 where a_date BETWEEN '18-NOV-2020' AND '18-
NOV-2021';

19) Write a query to find out the customer’s name who is living in city ‘Anand’ or
12302040701085 16
Krish solanki DBMS(202040302)

‘Ahmedabad’ from the table of CUSTOMER. i)


Using OR.
QUERY:
select c_name from CUSTOMER78 where city = 'Anand' OR city = 'Ahmedabad';

ii) Using IN.


QUERY:
select c_name from CUSTOMER78 where city IN('Anand', 'Ahmedabad');

20) Write a query to find out the customer’s name who is not living in city ‘Anand’ from
the table of CUSTOMER.
QUERY:
select c_name from CUSTOMER78 where NOT city = 'Anand';

12302040701085 17
Krish solanki DBMS(202040302)

21) Write a query to find out the customer’s name who is neither living in city ‘Anand’
nor in
‘Ahmedabad’ from the table of CUSTOMER. i)
Using NOT.
QUERY:
select c_name from CUSTOMER78 where NOT city = 'Anand' AND NOT city
= 'Ahmedabad';

ii)
Using NOT IN.
QUERY:
select c_name from CUSTOMER78 where city NOT IN('Anand', 'Ahmedabad');

22) Write a query to display the details of the table DEPOSIT in ascending order by
name.
QUERY: select * from DEPOSITE78 ORDER BY
c_name ASC;

12302040701085 18
Krish solanki DBMS(202040302)

23) Write a query to display the details of the table DEPOSIT in Descending order by
name.
QUERY: select * from DEPOSITE78 ORDER BY
c_name DESC;

12302040701085 19
Krish solanki DBMS(202040302)

PRACTICAL-4 SQL Single Row Functions


1) Write a query to convert the string in c_name to Upper Case from the table of
CUSTOMER.
QUERY: select UPPER(c_name) from
CUSTOMER78;

2) Write a query to convert the string in c_name to Lower Case from the table of
CUSTOMER.
QUERY: select LOWER(c_name) from
CUSTOMER78;

12302040701085 20
Krish solanki DBMS(202040302)

3) Write a query to convert the string in c_name by Capping Initial Letter from the table
of
CUSTOMER.
QUERY: select INITCAP(c_name) from
CUSTOMER78;

4) Write a query to concatenate string ‘Hello! ‘ and string in c_name from the table of
CUSTOMER.
QUERY: select CONCAT('Hello! ', c_name) from
CUSTOMER78;

12302040701085 21
Krish solanki DBMS(202040302)

5) Write a query to create substring starting from 2nd position and having size of 4 from
c_name from the table of CUSTOMER.
QUERY: select SUBSTR(c_name, 2, 4) from
CUSTOMER78;

6) Write a query to find out the position of character ‘a’ of c_name from the table of
CUSTOMER.
QUERY:
select INSTR(c_name, 'a') from CUSTOMER78;

12302040701085 22
Krish solanki DBMS(202040302)

7) Write a query to fill remaining places (padding) with ‘_’ of c_name having string size
of 10 from the table of CUSTOMER. i) Using RPAD (Right Padding).
QUERY:
select RPAD(c_name, 10, '_') from CUSTOMER78;

ii)
Using LPAD (Left Padding).
QUERY:
select LPAD(c_name, 10, '_') from CUSTOMER78;

8) Write a query to round the number 123.456 to 2 decimal place.


QUERY:
select ROUND(123.456, 2) from dual;

12302040701085 23
Krish solanki DBMS(202040302)

9) Write a query to round the number 123.456 to -1 decimal place.


QUERY:
select ROUND(123.456, -1) from dual;

10) Write a query to truncate the number 123.456 to 2 decimal place.


QUERY:
select TRUNC(123.456, 2) from dual;

11) Write a query to truncate the number 123.456 to -1 decimal place.


QUERY:
select TRUNC(123.456, -1) from dual;

12) Write a query to display the current date of the database.


QUERY:
select sysdate from dual;

12302040701085 24
Krish solanki DBMS(202040302)

13) Write a query to display the current time of the database.


QUERY:
select systimestamp from dual;

14) Write a query to find out the customer’s account number and since how many days
that customer has opened their account from the table of DEPOSIT.
QUERY:
select act_no, (sysdate - a_date) from DEPOSITE78;

15) Write a query to find out the customer’s account number and since how many months
that customer has opened their account from the table of DEPOSIT.
QUERY: select act_no, MONTHS_BETWEEN(sysdate, a_date) from
DEPOSITE78;

12302040701085 25
Krish solanki DBMS(202040302)

16) Write a query to find out the resultant month by adding 2 months to the current month
from the system.
QUERY:
select ADD_MONTHS(sysdate, 2) from dual;

17) Write a query to find out the last day of month from the system.
QUERY:
select LAST_DAY(sysdate) from dual;

18) Write a query to find out the date of next Sunday respective to the current date from
system.
QUERY:
select NEXT_DAY(sysdate, 1) from dual;

12302040701085 26
Krish solanki DBMS(202040302)

19) Write a query to display the act_no, c_name, b_name from DEPOSIT and amount
increase by 15% and label the column name as ’new_amount’.
QUERY:
select act_no, c_name, b_name, (amount*1.15) as new_amount from DEPOSITE78;

12302040701085 27
Krish solanki DBMS(202040302)

PRACTICAL-5
SQL Multiple Row Functions (Aggregate Function) 1)
Write a query to display minimum amount from DEPOSIT.
QUERY:
select min(amount) from DEPOSITE78;

2) Write a query to display minimum amount from DEPOSIT and label it as


‘min_amount’.
QUERY:
select min(amount) as min_amount from DEPOSITE78;

3) Write a query to display maximum amount from DEPOSIT.


QUERY:
select max(amount) from DEPOSITE78;

12302040701085 28
Krish solanki DBMS(202040302)

4) Write a query to display the total number of accounts from the table DEPOSIT.
QUERY:
select count(act_no) from DEPOSITE78;

5) Write a query to display the average amount from DEPOSIT.


QUERY: select AVG(amount) from
DEPOSITE78;

6) Write a query to display the sum of amount from DEPOSIT.


QUERY: select SUM(amount) from
DEPOSITE78;

7) Write a query to list out the number of customers in each city from the table of
CUSTOMER.
QUERY:
select city, count(c_name) from CUSTOMER78 GROUP BY city;

12302040701085 29
Krish solanki DBMS(202040302)

8) Write a query to list out the number of customers in each city sorted high to low from
the table of CUSTOMER.
QUERY:
select city, count(c_name) from CUSTOMER78 GROUP BY city ORDER BY count(c_name)
DESC;

9) Write a query to list out the number of customers living in same cities from the table
of
CUSTOMER.
QUERY: select city, count(c_name) from CUSTOMER78 GROUP BY city HAVING
count(c_name) >= 2;

10) Write a query to display the name of distinct cities from the table of CUSTOMER.
QUERY: select DISTINCT city from
CUSTOMER78;

12302040701085 30
Krish solanki DBMS(202040302)

11) Write a query to display the number of distinct cities from the table of CUSTOMER.
QUERY: select count(DISTINCT city) from
CUSTOMER78;

PRACTICAL-6
Displaying Data from Multiple Tables (Join)

1)Write a query to display the details of required customer.


QUERY:
select d.act_no, d.c_name, d.amount, d.a_date, c.city, b.b_name, b.city from DEPOSIT d,
BRANCH b, CUSTOMER c WHERE d.c_name = c.c_name AND d.b_name = b.b_name
AND d.c_name = '';

2) Write a query to find out the customers’ name who are depositor as well as borrower and
living in city ‘Vadodara’.
QUERY:
select c.c_name from CUSTOMER c, DEPOSIT d, BORROW b WHERE c.c_name =
d.c_name AND c.c_name = b.c_name AND c.city = 'Vadodara';

12302040701085 31
Krish solanki DBMS(202040302)

3) Write a query to find out that city in which customer is living is same as city of branch.
QUERY:
select c.city from CUSTOMER c, BRANCH b WHERE c.city = b.city;

4) Write a query to display the employee name, department number, department name
for all employees.
QUERY:
select e.e_name, e.d_no, d.d_name from EMPLOYEE e, DEPARTMENT d WHERE e.d_no =
d.d_no;

5) Write a query to create unique listing of all jobs that are in department
number ‘102’. Include the location of department in output. QUERY:
select j.j_id, j.j_title, e.d_no, d.d_location from JOBS j, EMPLOYEE e,
DEPARTMENT d WHERE j.j_id = e.j_id AND e.d_no = d.d_no AND
e.d_no = 102;

12302040701085 32
Krish solanki DBMS(202040302)

6) Write a query to display the employee name, department number,


department name for all employees who work in ‘New York’. QUERY:
select e.e_name, e.d_no, d.d_name from EMPLOYEE e, DEPARTMENT d
WHERE e.d_no = d.d_no AND d_location = 'New York';

PRACTICAL-7
Using Commit and Rollback show Transaction ACID Property A
transaction is a unit of work that is performed against a database. Transactions are units
sequences of work accomplished in a logical order, whether in a manual fashion by a user
or automatically by some sort of a database program.

A transaction is the propagation of one or more changes to the database. For example, if
you are creating a record or updating a record or deleting a record from the table, then
you are performing a transaction on that table. It is important to control these transactions
to ensure the data integrity and to handle database errors.

Practically, you will club many SQL queries into a group and you will execute all of them
together as a part of a transaction.

Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID.

1) ATOMICITY − ensures that all opera ons within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure and all
the previous operations are rolled back to their former state.
2) CONSISTENCY − ensures that the database properly changes states upon a
successfully committed transaction.
3) ISOLATION − enables transac ons to operate independently of and transparent
to each other.
4) DURABILITY − ensures that the result or effect of a committed transaction
persists in case of a system failure.

12302040701085 33
Krish solanki DBMS(202040302)

Transaction Control
The following commands are used to control transactions.

1) COMMIT − to save the changes.


2) ROLLBACK − to roll back the changes.
3) SAVEPOINT − creates points within the groups of transac ons in which to
ROLLBACK.
4) TRANSACTION − places a name on a transaction.

Transactional Control Commands


Transactional control commands are only used with the DML Commands such as -
INSERT, UPDATE and DELETE only. They cannot be used while creating tables or
dropping them because these operations are automatically committed in the database.

The COMMIT Command


The COMMIT command is the transactional command used to save changes invoked
by a transaction to the database.

The COMMIT command is the transactional command used to save changes invoked
by a transaction to the database. The COMMIT command saves all the transactions to
the database since the last COMMIT or ROLLBACK command.

The syntax for the COMMIT command is as follows: COMMIT;


Example

Consider the CUSTOMERS table having the following records:

ID NAME AGE ADDRESS SALARY


1 Juned 19 Anand 1000000.00
2 Mitesh 18 Ahmedabad 500000.00
3 Hitesh 20 Anand 400000.00
4 Pooja 20 Vadodara 300000.00

Following is an example which would delete those records from the table which have
age = 18 and then COMMIT the changes in the database.
SQL> DELETE FROM CUSTOMERS WHERE AGE = 18;
SQL> COMMIT;
Thus, two rows from the table would be deleted and the SELECT statement would
produce as below:
ID NAME AGE ADDRESS SALARY
1 Juned 19 Anand 1000000.00
3 Hitesh 20 Anand 400000.00

12302040701085 34
Krish solanki DBMS(202040302)

4 Pooja 20 Vadodara 300000.00

The ROLLBACK Command


The ROLLBACK command can only be used to undo transactions since the last
COMMIT or ROLLBACK command was issued. The syntax for a ROLLBACK
command is as follows:
ROLLBACK;
Example

Consider the CUSTOMERS table having the following records:


ID NAME AGE ADDRESS SALARY
1 Juned 19 Anand 1000000.00
2 Mitesh 18 Ahmedabad 500000.00
3 Hitesh 20 Anand 400000.00
4 Pooja 20 Vadodara 300000.00

Following is an example, which would delete those records from the table which
have the age = 18 and then ROLLBACK the changes in the database.

SQL> DELETE FROM CUSTOMERS WHERE AGE = 18;


SQL> ROLLBACK;
Thus, the delete operation would not impact the table and the SELECT statement
would produce the following result.
I AG
D NAME E ADDRESS SALARY
1 Juned 19 Anand 1000000.00
2 Mitesh 18 Ahmedabad 500000.00
3 Hitesh 20 Anand 400000.00
4 Pooja 20 Vadodara 300000.00

The SAVEPOINT Command


A SAVEPOINT is a point in a transaction when you can roll the transaction back to a
certain point without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below:
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the
transactional statements. The ROLLBACK command is used to undo a group
of transactions. The syntax for rolling back to a SAVEPOINT is as shown
below:
ROLLBACK TO SAVEPOINT_NAME;
12302040701085 35
Krish solanki DBMS(202040302)

Following is an example where you plan to delete the three different records from the
CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you
can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its
original state.
Example

Consider the CUSTOMERS table having the following records.


The following code block contains the series of operations.

I AG
D NAME E ADDRESS SALARY
1 Juned 19 Anand 1000000.00
2 Mitesh 18 Ahmedabad 500000.00
3 Hitesh 20 Anand 400000.00
4 Pooja 20 Vadodara 300000.00

SQL> SAVEPOINT SP1;


Savepoint created.

SQL> DELETE FROM CUSTOMERS


WHERE ID=1; 1 row deleted.

SQL> SAVEPOINT SP2;


Savepoint created.
SQL> DELETE FROM CUSTOMERS
WHERE ID=2; 1 row deleted.

SQL> SAVEPOINT SP3;


Savepoint created.
SQL> DELETE FROM CUSTOMERS
WHERE ID=3; 1 row deleted.

Now that the three deletions have taken place, let us assume that you have changed
your mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2.
Because SP2 was created after the first deletion, the last two deletions are undone:

SQL> ROLLBACK TO
SP2; Rollback complete.

Notice that only the first deletion took place since you rolled back to SP2.

SQL> SELECT * FROM CUSTOMERS

12302040701085 36
Krish solanki DBMS(202040302)

ID NAME AGE ADDRESS SALARY


2 Mitesh 18 Ahmedabad 500000.00
3 Hitesh 20 Anand 400000.00
4 Pooja 20 Vadodara 300000.00

The RELEASE SAVEPOINT Command


The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have
created.
The syntax for a RELEASE SAVEPOINT command is as follows:
RELEASE SAVEPOINT SAVEPOINT_NAME;
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the last SAVEPOINT.

The SET TRANSACTION Command


The SET TRANSACTION command can be used to initiate a database transaction. This
command is used to specify characteristics for the transaction that follows. For
example, you can specify a transaction to be read only or read write.
SQL language is divided into four types of primary language statements: DML, DDL,
DCL and TCL. Using these statements, we can define the structure of a database by
creating and altering database objects, and we can manipulate data in a table through
updates or deletions. We also can control which user can read/write data or manage
transactions to create a single unit of work.

TCL (Transaction Control Language)


TCL statements allow you to control and manage transactions to maintain the
integrity of data within SQL statements.

1) BEGIN Transaction – opens a transaction.

2) COMMIT Transaction – commits a transaction.

3) ROLLBACK Transaction – ROLLBACK a transaction in case of any error.

Difference between ROLLBACK and COMMIT commands:

ROLLBACK COMMIT
The COMMIT command is used to
ROLLBACK command is used to save the modification done to the
undo the changes made by the DML database values by the DML
commands. commands.
It will make all the changes
It rollbacks all the changes of the
12302040701085 37
Krish solanki DBMS(202040302)

permanent that cannot be rolled


current transaction. back.
Syntax:
DELETE FROM table_name Syntax:
ROLLBACK; COMMIT;

PRACTICAL-8
Securing data using Views and Controlling User Access (DCL)
Introduction to Privileges
A privilege is a right to execute a particular type of SQL statement or to access another user's
object. Some examples of privileges include the right to:

• Connect to the database (create a session).

• Create a table.

• Select rows from another user's table.

• Execute another user's stored procedure.

DCL (Data Control Language)


• DCL statements control the level of access that users have on database objects.

• GRANT – allows users to read/write on certain database objects.

• REVOKE – keeps users from read/write permission on database objects.


You grant privileges to users so these users can accomplish tasks required for their job.
You should grant a privilege only to a user who absolutely requires the privilege to
accomplish necessary work. Excessive granting of unnecessary privileges can
compromise security. A user can receive a privilege in two different ways:

• You can grant privileges to users explicitly. For example, you can explicitly grant the
privilege to insert records into the employees table to the user SCOTT.
• You can also grant privileges to a role (a named group of privileges), and then grant
the role to one or more users. For example, you can grant the privileges to select,
12302040701085 38
Krish solanki DBMS(202040302)

insert, update, and delete records from the employees table to the role named clerk,
which in turn you can grant to the users scott and brian.

Because roles allow for easier and better management of privileges, you should
normally grant privileges to roles and not to specific users. There are two types of
different privileges:
1. System privileges

2. Schema object privileges

System privileges
A system privilege is the right to perform a particular action, or to perform an action on any
schema objects of a particular type. For example, the privileges to create table spaces and to
delete the rows of any table in a database are system privileges. There are over 60 distinct
system privileges.

Grant and Revoke System Privileges

You can grant or revoke system privileges to users and roles. If you grant system privileges
to roles, then you can use the roles to manage system privileges. For example, roles permit
privileges to be made selectively available.
Use either of the following to grant or revoke system privileges to users and roles:

Oracle Enterprise Manager Console


The SQL statements GRANT and REVOKE

Who Can Grant or Revoke System Privileges?


Only users who have been granted a specific system privilege with the ADMIN OPTION or
users with
the system privileges GRANT ANY PRIVILEGE or GRANT ANY
OBJECT PRIVILEGE can grant or revoke system privileges to
other users.

Schema Object Privileges

A schema object privilege is a privilege or right to perform a particular action on a specific


schema object:
• Table

• View

• Sequence

• Procedure

• Function

• Package

12302040701085 39
Krish solanki DBMS(202040302)

Different object privileges are available for different types of schema objects. For example,
the privilege to delete rows from the departments table is an object privilege.
Some schema objects, such as clusters, indexes, triggers, and database links, do not have
associated object privileges. Their use is controlled with system privileges. For example,
to alter a cluster, a user must own the cluster or have the ALTER ANY CLUSTER system
privilege. A schema object and its synonym are equivalent with respect to privileges. That
is, the object privileges granted for a table, view, sequence, procedure, function, or
package apply whether referencing the base object by name or using a synonym.
For example, assume there is a table jward.emp with a synonym named jward.employee
and the user jward issues the following statement:

GRANT SELECT ON emp TO swilliams;


The user swilliams can query jward.emp by referencing the table by name or using the
synonym jward.employee:

SELECT * FROM jward.emp;


SELECT * FROM jward.employee;
If you grant object privileges on a table, view, sequence, procedure, function, or package to
a synonym for the object, the effect is the same as if no synonym were used. For example,
if jward wanted to grant the SELECT privilege for the emp table to swilliams, jward could
issue either of the following statements:

GRANT SELECT ON emp TO swilliams;


GRANT SELECT ON employee TO swilliams;
If a synonym is dropped, all grants for the underlying schema object remain in effect,
even if the privileges were granted by specifying the dropped synonym.

Grant and Revoke Schema Object Privileges

Schema object privileges can be granted to and revoked from users and roles. If you grant
object privileges to roles, you can make the privileges selectively available. Object privileges
for users and roles can be granted or revoked using the following:
• The SQL statements GRANT and REVOKE, respectively

• The Add Privilege to Role/User dialog box and the Revoke Privilege from Role/User
dialog box of Oracle Enterprise Manager.

Who Can Grant Schema Object Privileges?


A user automatically has all object privileges for schema objects contained in his or her
schema. A user can grant any object privilege on any schema object he or she owns to any
other user or role. A user with the GRANT ANY OBJECT PRIVILEGE can grant or
revoke any specified object privilege to another user with or without the GRANT
OPTION of the GRANT statement.
Otherwise, the grantee can use the privilege, but cannot grant it to other users.
For example, assume user SCOTT has a table named t2:
SQL>GRANT grant any object privilege TO U1;
12302040701085 40
Krish solanki DBMS(202040302)

SQL> connect u1/u1


Connected.
SQL> GRANT select on scott.t2 \TO U2;
SQL> SELECT GRANTEE, OWNER, GRANTOR, PRIVILEGE, GRANTABLE FROM
DBA_TAB_PRIVS WHERE TABLE_NAME = 'employees';
GRANTEE OWNER GRANTOR PRIVILEGE GRANTABLE
U2 SCOTT SCOTT SELECT NO

Privileges Required to Create Views

To create a view, you must meet the following requirements:


You must have been granted one of the following system privileges, either explicitly or
through a role:

• The CREATE VIEW system privilege (to create a view in your schema).

• The CREATE ANY VIEW system privilege (to create a view in another user's
schema).

You must have been explicitly granted one of the following privileges:
• The SELECT, INSERT, UPDATE, or DELETE object privileges on all base objects
underlying the view.

• The SELECT ANY TABLE, INSERT ANY TABLE, UPDATE ANY TABLE, or
DELETE ANY TABLE system privileges.

Additionally, in order to grant other user’s access to your view, you must have received
object privileges to the base objects with the GRANT OPTION clause or appropriate
system privileges with the ADMIN OPTION clause. If you have not, grantees cannot
access your view.

Increase Table Security with Views

To use a view, you require appropriate privileges only for the view itself. You do not require
privileges on base objects underlying the view.

Views add two more levels of security for tables, column-level security and value-based
security:

• A view can provide access to selected columns of base tables. For example, you can
define a view on the employees table to show only the employee_id, last_name, and
manager_id columns:

CREATE VIEW employees_manager AS SELECT last_name, employee_id,


manager_id FROM employees;

12302040701085 41
Krish solanki DBMS(202040302)

• A view can provide value-based security for the information in a table. A WHERE
clause in the definition of a view displays only selected rows of base tables. Consider
the following two examples:

CREATE VIEW lowsal AS SELECT * FROM employees WHERE salary < 10000;

• The LOWSAL view allows access to all rows of the employees table that have a
salary value less than 10000. Notice that all columns of the employees table are
accessible in the LOWSAL view.

CREATE VIEW own_salary AS SELECT last_name, salary FROM employees


WHERE last_name = USER;

In the own_salary view, only the rows with an last_name that matches the current
user of the view are accessible. The own_salary view uses the user pseudocolumn,
whose values always refer to the current user. This view combines both columnlevel
security and valuebased security.

PRACTICAL-9
PL/SQL Block System And DML Operation Through PL/SQL Block.

In PL/SQL, the code is not executed in single line format, but it is always executed by
grouping the code into a single element called Blocks.
Blocks contain both PL/SQL as well as SQL instruction. All these instructions will be
executed as a whole rather than executing a single instruction at a time.

BLOCK STRUCTURE:

PL/SQL blocks have a pre-defined structure in which the code is to be grouped.


The different sections of PL/SQL block are as follows:
1. Declaration section
2. Execution section
3. Termination section

1) Declaration section:

This is the first section of the PL/SQL blocks.


This section is an optional part.
This is the section in which the declaration of variables, cursors, exceptions,
subprograms, pragma instructions and collections that are needed in the block will be
declared.
This section starts with the keyword ‘DECLARE’ for triggers and anonymous block. For
other subprograms, this keyword will not be present. Instead, the part after the
subprogram name definition marks the declaration section.

2) Execution section:
12302040701085 42
Krish solanki DBMS(202040302)

Execution part is the main and mandatory part which actually executes the code that is
written inside it. Since the PL/SQL expects the executable statements from this block this
cannot be an empty block, i.e., it should have at least one valid executable code line in it.
This can contain one or many blocks inside it as a nested block.
This section starts with the keyword ‘BEGIN’.

3) Termination section:

This is the last section of the PL/SQL


blocks. This section is a mandatory part.
This section should always be followed by the keyword ‘END’.
The Keyword ‘END’ marks the end of PL/SQL block.
PL/SQL Block syntax:

declare
(Declaration of variable must be done here)

begin
(Logic of the program must be written here)

end;
/
(Termination of program takes place here)

DML operation through PL/SQL block:

DML stands for Data Manipulation Language.


These statements are mainly used to perform the manipulation activity.
It includes the below given operations:
• Data insertion
• Data update
• Data deletion
• Data selection
In PL/SQL, we can do the data manipulation only by using the SQL commands.

1) Data insertion:

In PL/SQL, we can insert the data into any table using the SQL command INSERT INTO.
This command will take the table name, table column and column values as the input and
insert the value in the base table.
The INSERT command can also take the values directly from another table using ‘SELECT’
statement rather than giving the values for each column. Through ‘SELECT’ statement, we
can insert as many rows as the base table contains.

• Syntax:
12302040701085 43
Krish solanki DBMS(202040302)

(i) BEGIN
INSERT INTO <table_name>(<column1 >,<column2>,...<column_n>)
VALUES(<value1><value2>,...:<value_n>);
END;
/

• The above syntax shows the INSERT INTO command. The table name and values are
mandatory fields, whereas column names are not mandatory if the insert statements
have values for all the column of the table.

• The keyword ‘VALUES’ is mandatory if the values are given separately as shown
above.

OR

(ii) BEGIN
INSERT INTO <table_name>(<column1>,<column2>,...,<column_n>)
SELECT <column1>,<column2>,.. <column_n> FROM <table_name2>;
END;
/

• The above syntax shows the INSERT INTO command that takes the values directly
from the <table_name2> using the SELECT command.

• The keyword ‘VALUES’ should not be present in this case as the values are not given
separately.

• Block:

begin insert into


PERSON
values('&p_id','&p_name','&age','&salary'); end;
/

12302040701085 44
Krish solanki DBMS(202040302)

2) Data update:

Data update simply means an update of the value of any column in the table. This can be
done using ‘UPDATE’ statement. This statement takes the table name, column name and
value as the input and updates the data.

• Syntax:

BEGIN
UPDATE <table_name>
SET <column1>=<VALUE1>,<column2>=<value2>,<column_n>=<value_n>
WHERE <condition that uniquely identifies the record that needs to be update>;
END;
/

• The above syntax shows the UPDATE. The keyword ‘SET’ instruct that PL/SQL
engine to update the value of the column with the value given.
• ‘WHERE’ clause is optional. If this clause is not given, then the value of the
mentioned column in the entire table will be updated.

12302040701085 45
Krish solanki DBMS(202040302)

• Block:
set serveroutput
on begin update
PERSON
set p_name = 'Kesha' where p_id = '10005'; end;
/

3) Data deletion:
Data deletion means to delete one full record from the database table. The ‘DELETE’
command is used for this purpose.

• Syntax:
BEGIN
DELETE FROM<table_name> WHERE <condition that uniquely identifies the record that
needs to be update>;
END;
/

• The above syntax shows the DELETE command. The keyword ‘FROM’ is optional
and with or without ‘FROM’ clause the command behaves in the same way.
• ‘WHERE’ clause is optional. If this clause is not given, then the entire table will be
deleted.

• BLOCK:

set serveroutput on
begin
delete from PERSON where p_id = '10005'; end;
/

12302040701085 46
Krish solanki DBMS(202040302)

4) Data selection:
Data projection/fetching means to retrieve the required data from the database table. This can
be achieved by using the command ‘SELECT’ with ‘INTO’ clause. The ‘SELECT’ command
will fetch the values from the database, and ‘INTO’ clause will assign these values to the
local variable of the PL/SQL block.

• Below are the points that need to be considered in ‘SELECT’ statement.


‘SELECT’ statement should return only one record while using ‘INTO’ clause as one
variable can hold only one value. If the ‘SELECT’ statement returns more than one
value than ‘TOO_MANY_ROWS’ exception will be raised.

‘SELECT’ statement will assign the value to the variable in the ‘INTO’ clause, so it
needs to get at least one record from the table to populate the value. If it didn’t get any
record, then the exception ‘NO_DATA_FOUND’ is raised.

The number of columns and their datatype in ‘SELECT’ clause should match with
the number of variables and their datatypes in the ‘INTO’ clause.
The values are fetched and populated in the same order as mentioned in the statement.
‘WHERE’ clause is optional that allows to having more restriction on the records
that are going to be fetched.

‘SELECT’ statement can be used in the ‘WHERE’ condition of other DML


statements to define the values of the conditions.

The ‘SELECT’ statement when using ‘INSERT’, ‘UPDATE’, ‘DELETE’ statements


should not have ‘INTO’ clause as it will not populate any variable in these cases.

• Syntax:
12302040701085 47
Krish solanki DBMS(202040302)

BEGIN
SELECT <column 1 >, . ., <column_n> INTO <variable 1 >,. . , <variable_n> FROM
<table_name> WHERE <condition to fetch the required records>;
END;
/

• The above syntax shows the SELECT-INTO command. The keyword ‘FROM’ is
mandatory that identifies the table name from which the data needs to be fetched.
• ‘WHERE’ clause is optional. If this clause is not given, then the data from the
entire table will be fetched.

PRACTICAL-10
Control Structures in PL/SQL

(1) Write a PL/SQL block to check whether the given number is even or odd.

set serveroutput
on declare n
number:=&n;
12302040701085 48
Krish solanki DBMS(202040302)

begin if
mod(n,2)=0 then
dbms_output.put_line('Number is even.');
else
dbms_output.put_line('Number is
odd.'); end if; end;
/

(2) Write a PL/SQL block to find the sum of odd numbers between 1 to 100.

set serveroutput
on; declare n
number := 1; n1
number; s number
:= 0; begin loop
n1 := n
+ 2; s := s +
n1; exit when
n1 = 99; end
loop;
dbms_output.put_line('Sum of odd numbers between 1 to 100 is ' || s);
end;
/

12302040701085 49
Krish solanki DBMS(202040302)

(3) Write the PL/SQL block to find the factorial of the given number.

set serveroutput
on declare n
number := &n; i
number; f
number := 1;
begin for i in 1..n
loop
f := f*i;
end loop;
dbms_output.put_line(n||'! = '||f);
end;
/

12302040701085 50
Krish solanki DBMS(202040302)

(4) Write a PL/SQL block to generate Fibonacci series.

set serveroutput on
declare a number := 0; b
number := 1; c number;
begin dbms_output.put(a||'
'||b||' '); for i in 3..10 loop
c := a+b;
dbms_output.put(c||' ');
a :=b; b :=c; end loop;
dbms_output.put_line(' ');
end;
/

(5) Write a PL/SQL block to reverse a number.

set serveroutput
on declare n
number; s
number := 0; r
number; k
number; begin
n :=&n; k :=n;
loop exit when
n=0; s :=s*10;
r :=mod(n,10);
s :=s+r;

12302040701085 51
Krish solanki DBMS(202040302)

n :=trunc(n/10); end
loop;
dbms_output.put_line('The reversed digits of '||K||' = '||S);
end;
/
(6) Write a PL/SQL block to find the greatest of three numbers.

set serveroutput
on declare a
number := &a;
b number := &b;
c number := &c;
begin if a>b and
a>c then
dbms_output.put_line(a||' is greatest.');
elsif b>a and b>c then
dbms_output.put_line(b||' is greatest.');
else
dbms_output.put_line(c||' is greatest.');
end if;
end;
/

(7) Write a PL/SQL block to find area of circles with radius greater than 3 and less than
equal to 7 and store the result in a table with attributes radius and area.

set serveroutput on declare


area number(5,2); radius
number(1):=3; pi constant
number(3,2):=3.14;
begin while
radius<=7 loop
area:=pi*radius*radius; insert
into areas values(radius,area);
radius:=radius+1; end loop;
end;
12302040701085 52
Krish solanki DBMS(202040302)

/
PRACTICAL-11
Working with Cursor

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.
In 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:

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.

12302040701085 53
Krish solanki DBMS(202040302)

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: o We will be using the EMPLOYEE table we
had created earlier.

o The following program will update the table and increase the salary of each employee by
5000 and use the SQL%ROWCOUNT attribute to determine the number of rows affected:
set serveroutput on; declare
total_rows number(2);
begin
update EMPLOYEE set e_salary = e_salary + 5000; if
sql%notfound then dbms_output.put_line('No employees
selected'); elsif sql%found then total_rows := sql
%rowcount; dbms_output.put_line(total_rows || '
employees selected'); end if; end;
/
o When the above code is executed at the SQL prompt, it produces the following result:

12302040701085 54
Krish solanki DBMS(202040302)

o If you check the records in EMPLOYEE table, you will find that the rows have been
updated:

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.
The syntax for creating an explicit cursor is:
CURSOR cursor_name IS select_statement;
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 emp_details IS SELECT e_no, e_name, e_salary from EMPLOYEE;
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 emp_details;
Fetching the Cursor:
12302040701085 55
Krish solanki DBMS(202040302)

Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows:

FETCH emp_details into emp_no, emp_name, emp_salary;

Closing the Cursor:


Closing the cursor means releasing the allocated memory. For example, we will close the
aboveopened cursor as follows:
CLOSE emp_details;

Example:
o Following is a complete example to illustrate the concepts of explicit cursors:
set serveroutput on; declare
emp_no EMPLOYEE.e_no%type;
emp_name EMPLOYEE.e_name%type;
emp_salary EMPLOYEE.e_salary%type;
CURSOR emp_details IS SELECT e_no, e_name, e_salary from
EMPLOYEE; begin
OPEN emp_details;
loop
FETCH emp_details into emp_no, emp_name, emp_salary;
exit when emp_details%notfound;
dbms_output.put_line(emp_no || ' ' || emp_name || ' ' || emp_salary); end loop;
CLOSE emp_details; end;
/

o When the above code is executed at the SQL prompt, it produces the following result:

12302040701085 56
Krish solanki DBMS(202040302)

PRACTICAL-12
Creating Procedures and Functions in PL/SQL

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.
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.

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
1 start with 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.

12302040701085 57
Krish solanki DBMS(202040302)

Creating a Procedure:
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and
over again.
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}
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:
o The following example creates a simple procedure that displays the string 'Hello!' on the
screen when executed.
set serveroutput on; create
PROCEDURE greetings AS begin
dbms_output.put_line('Hello!'); end;
/

o When the above code is executed using the SQL prompt, it will produce the following
result:

12302040701085 58
Krish solanki DBMS(202040302)

Executing a Standalone Procedure:

o A standalone procedure can be called in two ways:


• Using the EXECUTE keyword
• Calling the name of the procedure from a PL/SQL block

o The above procedure named 'greetings' can be called with the EXECUTE keyword as:
EXECUTE greetings; o

The above call willdisplay:

o The procedure can also be called from another PL/SQL block:


begin greetings;

end;
/

o The above call will display:

Deleting a Standalone Procedure:

A standalone procedure is deleted with the DROP PROCEDURE statement. o


Syntax for deleting a procedure is:

DROP PROCEDURE procedure-name; o You can drop the greetings procedure

by using the following statement: drop PROCEDURE greetings;

12302040701085 59
Krish solanki DBMS(202040302)

Parameter Modes in PL/SQL Subprograms:


The following table lists out the parameter modes in PL/SQL subprograms:

S.No Parameter Mode & Description

1 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. 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.

2 OUT:
An OUT parameter returns a value to the calling program. Inside the subprogram,
an OUT 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.

3
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.
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:


o 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;
12302040701085 60
Krish solanki DBMS(202040302)

c
number;
PROCED
URE
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 :=
10; b :=
20;
findMin(
a, b,
c); dbms_output.put_line('Minimum of (' || a || ', ' || b || ') : '
|| c); end;
/

o When the above code is executed at the SQL prompt, it produces the following result:

12302040701085 61
Krish solanki DBMS(202040302)

IN & OUT Mode Example 2:


o 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.
declare a number;
PROCEDURE squareNum(x IN OUT number)
IS begin

x := x * x;
end;
begin
a := 9;
squareNum(a);
dbms_output.put_line('Square of (9) : ' || a); end;
/
o When the above code is executed at the SQL prompt, it produces the following result:
o

Creating a Function:
A function is same as a procedure except that it returns a value.
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
12302040701085 62
Krish solanki DBMS(202040302)

< function_body >


END [function_name];
Where,

• 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: o We will use the EMPLOYEE table, which we had


created earlier:

o The following example illustrates how to create and call a standalone function. This function
returns the total number of employees in the EMPLOYEE table.
set serveroutput on; create
FUNCTION total_employees
RETURN number IS total
number(2) := 0; begin
select count(*) into total from EMPLOYEE;
RETURN total;
end;
/
o When the above code is executed using the SQL prompt, it will produce the following
result:

12302040701085 63
Krish solanki DBMS(202040302)

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.
o Following program calls the function total_employees from an anonymous block:
declare c
number(2);
begin
c := total_employees();
dbms_output.put_line('Total no. of employees : ' || c); end;
/
o When the above code is executed at the SQL prompt, it produces the following result:

Example:

o The following example demonstrates Declaring, Defining, and Invoking a Simple


PL/SQL Function that computes and returns the maximum of two values:
set serveroutput
on; declare a

12302040701085 64
Krish solanki DBMS(202040302)

number; b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN
number IS z
number; begin if
x > y then z :=
x; else z := y;
end if;
RETURN z;
end; begin a :=
10; b := 20; c :=
findMax(a, b);
dbms_output.put_line('Maximum of (' || a || ', ' || b || ') : ' || c); end;
/

o When the above code is executed at the SQL prompt, it produces the following result:

PL/SQL Recursive Functions:


We have seen that a program or subprogram may call another subprogram. When a
subprogram calls itself, it is referred to as a recursive call and the process is known as
recursion.
To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n
is defined as:

n! = n*(n-1)!
= n*(n-1)*(n-2)!
12302040701085 65
Krish solanki DBMS(202040302)

...
= n*(n-1)*(n-2)*(n-3)... 1

o The following program calculates the factorial of a given number by calling itself
recursively:

set serveroutput on; declare


num number;
factorial number;
FUNCTION fact(x
number) RETURN
number IS f number; begin
if x = 0 then
f := 1; else
f := x * fact(x - 1); end
if;
RETURN f; end; begin
num := 9; factorial :=
fact(num);
dbms_output.put_line('Factorial of ' || num || ' is ' || factorial); end;
/

o When the above code is executed at the SQL prompt, it produces the following result:

12302040701085 66
Krish solanki DBMS(202040302)

PRACTICAL-13
Creating Database Triggers

Triggers are stored programs, which are automatically executed or fired when some events occur.
Triggers are, in fact, written to be executed in response to any of the following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE) A database
definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.

Benefits of Triggers:
Triggers can be written for the following purposes:

• Generating some derived column values automatically


• Enforcing referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions

Creating Triggers:
The syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
12302040701085 67
Krish solanki DBMS(202040302)

ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
• CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing
trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF}: This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
• [OF col_name]: This specifies the column name that will be updated.
• [ON table_name]: This specifies the name of the table associated with the trigger.
• [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for
various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW]: This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise, the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
• WHEN (condition): This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.

Example:

o To start with, we will be using the EMPLOYEE table we had created and used in the
previous chapters:

o The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the EMPLOYEE table. This trigger
will display the salary difference between the old values and new values:

set serveroutput on;

12302040701085 68
Krish solanki DBMS(202040302)

create TRIGGER display_salary_changes BEFORE


delete OR insert OR update on
EMPLOYEE FOR EACH ROW when
(new.e_no > 0)
declare sal_diff
number; begin
sal_diff := :new.e_salary - :old.e_salary;
dbms_output.put_line('Old salary: ' || :old.e_salary);
dbms_output.put_line('New salary: ' || :new.e_salary);
dbms_output.put_line('Salary difference: ' || sal_diff); end;
/

o When the above code is executed at the SQL prompt, it produces the following result:

The following points need to be considered here:


• OLD and NEW references are not available for table-level triggers, rather you can use
them for record-level triggers.
• If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
• The above trigger has been written in such a way that it will fire before any DELETE
or INSERT or UPDATE operation on the table, but you can write your trigger on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table
Triggering a Trigger:

o Let us perform some DML operations on the EMPLOYEE table. Here is one INSERT
statement, which will create a new record in the table:

insert into EMPLOYEE values('&e_no', '&e_name', '&e_salary', '&e_contact_no',


'&d_no', '&j_id');
12302040701085 69
Krish solanki DBMS(202040302)

o When a record is created in the EMPLOYEE table, the above created trigger,
display_salary_changes will be fired and it will display the following result:

o Because this is a new record, old salary is not available and the above result comes as
null. Let us now perform one more DML operation on the EMPLOYEE table. The
UPDATE statement will update an existing record in the table:
update EMPLOYEE set e_salary = e_salary + 5000 where e_no = 10005;

o When a record is updated in the EMPLOYEE table, the above created trigger,
display_salary_changes will be fired and it will display the following result:

12302040701085 70

You might also like