Samarth
Samarth
PRACTICAL-1
Creating and Manipulating Database objects and Applying Constraints (DDL)
12302040701085
1
Krish solanki DBMS(202040302)
12302040701085
2
Krish solanki DBMS(202040302)
12302040701085
3
Krish solanki DBMS(202040302)
PRACTICAL-2
Manipulating Data with Database Objects (DML)
12302040701085
4
Krish solanki DBMS(202040302)
12302040701085
5
Krish solanki DBMS(202040302)
12302040701085
6
Krish solanki DBMS(202040302)
12302040701085
7
Krish solanki DBMS(202040302)
12302040701085
8
Krish solanki DBMS(202040302)
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;
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)
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)
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;
12302040701085 23
Krish solanki DBMS(202040302)
12302040701085 24
Krish solanki DBMS(202040302)
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;
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;
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)
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)
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.
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.
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)
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.
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
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
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.
12302040701085 36
Krish solanki DBMS(202040302)
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)
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:
• Create a table.
• 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
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.
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:
• 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:
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.
• 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.
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:
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.
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:
1) 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:
declare
(Declaration of variable must be done here)
begin
(Logic of the program must be written here)
end;
/
(Termination of program takes place here)
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:
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.
‘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.
• 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)
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;
/
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.
/
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:
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:
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows:
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.
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.
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
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)
o The above procedure named 'greetings' can be called with the EXECUTE keyword as:
EXECUTE greetings; o
end;
/
12302040701085 59
Krish solanki DBMS(202040302)
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.
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)
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)
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:
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:
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:
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:
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:
12302040701085 68
Krish solanki DBMS(202040302)
o When the above code is executed at the SQL prompt, it produces the following result:
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:
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