Database Management Systems Lab Guide
Database Management Systems Lab Guide
Lab manual
Course Coordinator
1
Diploma in Information Systems – Applied College Khamis Mushayt
Software(s)/Tools Used
Oracle 11g express edition
SQL developer as an editor
References
Lecture notes
http://www.w3schools.com/
Oracle SQL by Example 4th edition, Alice Rischert © 2009, ISBN-13: 978-0137142835
2
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #1
Introduction
ORACLE
It is a very large and multi-user database management system. Oracle is a relational database
management system developed by 'Oracle Corporation'.
Oracle works to efficiently manage its resource, a database of information, among the multiple
clients requesting and sending data in the network.
It is an excellent database server choice for client/server computing. Oracle supports all major
operating systems for both clients and servers, including MSDOS, NetWare, UnixWare, OS/2
and most UNIX flavors.
History:
Oracle began in 1977 and celebrating its 32 wonderful years in the industry (from 1977 to 2009).
1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development
Laboratories to undertake development work.
1979 - Version 2.0 of Oracle was released and it became first commercial relational
database and first SQL database. The company changed its name to Relational Software
Inc. (RSI).
1981 - RSI started developing tools for Oracle.
1982 - RSI was renamed to Oracle Corporation.
1983 - Oracle released version 3.0, rewritten in C language and ran on multiple
platforms.
1984 - Oracle version 4.0 was released. It contained features like concurrency control -
multi-version read consistency, etc.
1985 - Oracle version 4.0 was released. It contained features like concurrency control -
multi-version read consistency, etc.
2007 - Oracle has released Oracle11g. The new version focused on better partitioning,
easy migration, etc.
Features:
Concurrency
Read Consistency
Locking Mechanisms
Quiescent Database
Portability
Self-managing database
SQL*Plus
ASM
Scheduler
Resource Manager
3
Diploma in Information Systems – Applied College Khamis Mushayt
Data Warehousing
Materialized views
Bitmap indexes
Table compression
Parallel Execution
Analytic SQL
What is SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in relational database.
SQL is the standard language for Relation Database System. All relational database management
systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL
as standard database language.
Also, they are using different dialects, such as:
Why SQL?
SQL History:
4
Diploma in Information Systems – Applied College Khamis Mushayt
SQL Process:
When you are executing an SQL command for any RDBMS, the system determines the best way
to carry out your request and SQL engine figures out how to interpret the task.
There are various components included in the process. These components are Query Dispatcher,
Optimization Engines, Classic Query Engine and SQL Query Engine, etc. Classic query engine
handles all non-SQL queries, but SQL query engine won't handle logical files.
SQL Commands:
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These commands can be classified into groups based
on their nature:
5
Diploma in Information Systems – Applied College Khamis Mushayt
What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL and
for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access. A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model as introduced by E. F. Codd.
The data in RDBMS is stored in database objects called tables. The table is a collection of related
data entries and it consists of columns and rows. Every table is broken up into smaller parts called
fields. A field is a column in a table that is designed to maintain specific information about every
record in the table. A record, also called a row of data, is each individual entry that exists in a table.
6
Diploma in Information Systems – Applied College Khamis Mushayt
7
Diploma in Information Systems – Applied College Khamis Mushayt
8
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #2
Basic Concepts and Types of SQL commands
Aim: To give DBMS concepts and practice DDL and DML commands.
Objectives:
The objectives of this week are to:
1. Familiarize various type of SQL commands.
2. Practice some of DDL and DML commands
desc student
9
Diploma in Information Systems – Applied College Khamis Mushayt
Exercise
Exercise 1.1: Practice all the above commands with the course table given below.
10
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #3
DDL, DML and TCL commands
Aim: To use DDL, DML and TCL commands on a table.
Objectives:
1. To practice DDL to create, modify or drop a given table as shown below.
2. To practice DML commands to insert, update, delete and select the data.
3. To practice TCL commands to commit or rollback the data in the table.
DDL commands:
1. To delete or drop a table ( if exists )
drop table student;
desc student;
11
Diploma in Information Systems – Applied College Khamis Mushayt
desc student;
12
Diploma in Information Systems – Applied College Khamis Mushayt
Exercises
Exercise 2.1: Practice all the above commands for the course table given below.
Exercise 2.2: Practice all the above commands for the emp table given below.
(Hint: total=sal+overtime)
13
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #4
Database Constraints
Aim: To familiarize the database constraints on a table.
Objectives:
The objectives of this experiment are to:
1. Familiarize various types of database constraints.
2. Apply the following constraints on the table
a. primary Key
b. not null
c. check
d. foreign key
Note: We will practice above four constraints only in this week.
a. primary key: is a base or unique key applied on one (or set of more than one) column(s)
in each table. When applied the column value cannot be null. There can be only one
primary key per table.
b. not null: This constraint is applied on those columns which cannot be left empty like
name, course etc.
c. unique: is applied to those columns whose value will be unique like for example: idno,
mobileno, account_no etc.
d. check: will be applied to those columns to put restriction on the column value. For
example the marks of the student in student table like m1,m2,m3 can have the range
between 0 and 100.
Balance in the bank cannot be less than zero etc.
14
Diploma in Information Systems – Applied College Khamis Mushayt
The example below shows how to apply the above commands one the student table.
To create the following table with the above constraints.
univno Name Idno course m1 m2 m3 total
3. Drop the previous table student that you created in the last class
drop table student;
15
Diploma in Information Systems – Applied College Khamis Mushayt
Exercises
Exercise 3.1: Practice all the above commands with four constraints on the course table
given below:
Exercise 3.2: Practice all the above commands with the emp table given below.
16
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #5
Database Constraints – Foreign Key (Continued)
Primary Key
dep
dno Dname loc
Foreign Key
employee
empno ename mgr job sal comm dno
17
Diploma in Information Systems – Applied College Khamis Mushayt
desc dep
desc employee
2. Insert data into the master table first. Example is given below:
insert into dep values(10,’Accounting’,’Abha’);
insert into dep values(20,’Research,’Abha’);
insert into dep values(30,’Sales’,’ Khamis’);
3. Insert data into the detail table later. Example is given below:
insert into employee values
(1111,10,’Saad’,‘President’,null,20000,null);
18
Diploma in Information Systems – Applied College Khamis Mushayt
** You can NOT delete a row from the parent table (dept) that has related rows in the child table
(employee). To be able to do so, you have to delete all rows (foreign keys) in the child table first,
then you can delete from the parent table.
** We can use on delete cascade or on delete set null.
** To drop the tables, you have to drop the child table first then the parent table (the reverse order of
the table creation).Alternatively, you can use the following command to drop the tables on matter the
order of the table creation is.
Drop table table_name cascade constraints;
19
Diploma in Information Systems – Applied College Khamis Mushayt
Exercises
Exercise 4.1: Practice the same as above on the following two Baba and Bazura tables
given below:
Exercise 4.2: Practice the same as above on the following two teacher and course tables
given below:
20
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #6 & #7
Queries using select command and SQL operators
Aim: Implementing queries using select commands.
Objectives:
1. Various types of operators.
2. To implement these operators.
3. To use where clause
Logical Operators
and
or
not
21
Diploma in Information Systems – Applied College Khamis Mushayt
Tests for nulls. This is the only operator that should be used to
IS [NOT] NULL
test for nulls.
Wildcard Meaning
Character
The percent wildcard specifies that any characters can appear in multiple positions
%
represented by the wildcard.
_ The underscore wildcard specifies a single position in which any character can occur.
** To match a real % or _ (not any substring or character), add \ before the character.
22
Diploma in Information Systems – Applied College Khamis Mushayt
23
Diploma in Information Systems – Applied College Khamis Mushayt
LAB (Optinal)
Single row SQL Functions
Aim: To implement single row SQL functions.
Objectives:
The objectives of this experiment are to:
1. Describe various types of functions available in SQL.
2. Discuss about the single row functions.
3. Implement these functions with example data.
i) nvl
Example: select empno, ename, sal, nvl(comm,0) from emp;
ii) case
Example: select empno, ename, job, sal,
case job when ‘CLERK’ then sal*10/100
when ‘SALESMAN’ then sal*20/100
when ‘ANALYST’ then sal*40/100
24
Diploma in Information Systems – Applied College Khamis Mushayt
25
Diploma in Information Systems – Applied College Khamis Mushayt
ii) trunc:
Example: select trunc(56.63) from dual;
iii) mod
Example: select mod(10,2) from dual;
iv) ceil
Example: select ceil(15.3) from dual;
v) floor
Example: select floor(9.9) from dual;
4) Date functions:
i) NEXT_DAY
ii) ADD_MONTHS
iii) LAST_DAY
iv) MONTHS_BETWEEN
Examples:
SELECT SYSDATE FROM DUAL;
i) SELECT NEXT_DAY(SYSDATE,’WED’) FROM DUAL;
ii) SELECT ADD_MONTHS(SYSDATE,2) FROM DUAL;
iii) SELECT LAST_DAY(SYSDATE) FROM DUAL;
iv) SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE) FROM EMP;
5) Conversion functions
i) to_char
Examples:
a) SELECT TO_CHAR(SYSDATE,'DAY') FROM DUAL;
b) SELECT TO_CHAR(SYSDATE,'MONTH') FROM DUAL;
c) SELECT TO_CHAR(SYSDATE,'YEAR') FROM DUAL;
ii) to_date
How to calculate your age:
I) USING HIJRI ARABIC DATES:
SELECT MONTHS_BETWEEN(TO_DATE(’25-11-1432’,’DD-MM-YYYY’),
TO_DATE(’25-11-1409’,’DD-MM-YYYY’))/12 FROM DUAL;
II) USING GREGORIAN DATES:
26
Diploma in Information Systems – Applied College Khamis Mushayt
Exercises
Exercise 6.1: Demonstrate the general functions on emp table showing the increment of sal
column given below:
- for CLERK add 500 to the sal.
- for SALESMAN add 1500
- for ANALYST increment 50% to the basic salary
- for MANAGER increment 70% to the basic salary
- for PRESIDENT increment 80% to the basic salary.
Exercise 6.2: Demonstrate the character and number functions with different values.
27
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #8 & #9
Aggregating Data and Using Group Functions
Aim: Aggregate data using group functions.
Objectives: The objectives of this experiment are to:
1. Identify the available group functions.
2. Describe the use of group functions.
3. Group data using group by clause.
4. Include or exclude grouped rows by using having clause.
Some of the aggregate functions are:
a. sum
b. avg
c. max
d. min
e. count
Example commands for the above functions:
a. select sum(sal) from emp;
b. select avg(sal) from emp;
c. select max(sal) from emp;
d. select min(sal) from emp;
28
Diploma in Information Systems – Applied College Khamis Mushayt
iii. Count (distinct expr) - ; returns the number distinct non null rows identified by
expr.
Example: select count (distinct deptno) from emp;
Note:
1. You can use sum and avg functions for numeric data:
Example: select sum(sal), avg(sal), max(sal), min(sal) from emp;
2. You can use max and min functions for any type of data.
Example: select max(hiredate), min(hiredate) from emp;
ii) The group by clause column does not have to be in the select list.
Example: select sum(sal),avg(sal),max(sal),min(sal) from emp group by city;
29
Diploma in Information Systems – Applied College Khamis Mushayt
Order by clause
Syntax:
Order by column-list
Sorts the result according to specified criteria
Default is ascending order
Add desc if descending order
Example
Return employees by ascending order of their names
Select * from emp order by ename;
Return employees by decending order of their names
Select * from emp order by ename desc;
30
Diploma in Information Systems – Applied College Khamis Mushayt
Exercises
Exercise 7.1: Demonstrate the aggregate functions on emp table showing maximum, minimum,
sum and average salaries for managers and analysts.
Exercise 7.2: Demonstrate the aggregate functions on emp table showing maximum, minimum,
sum and average salaries using having clause for different departments.
31
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #10
Joins in SQL
Aim: To get acquainted with different types of joins.
Objectives: The objectives of this experiment are to:
1. Write SQL statements to access data from more than one table (two or Multi-Table Join).
2. Join a table to itself by using self-join.
3. View data that generally does not meet a join condition by using outer join (left outer
join, right outer join and full outer join.)
4. Perform set operations like union, intersection and minus.
A join: is a query that combines rows from two or more tables, views, or materialized views.
32
Diploma in Information Systems – Applied College Khamis Mushayt
Types of joins:
i) Equi join
ii) Non equi join
iii) Self join
iv) Inner Joins
v) Outer join
We will use the following two tables to apply different types of join queries.
Customers table
ID Name Age Address Salary supervisor_ID
1 Ahmad 32 Abha 2000 null
2 Ali 25 Jeddah 1500 null
3 Fawwaz 23 Makkah 2000 1
4 Fahad 25 Abha 6500 1
5 Sultan 32 Najran 8500 1
6 Ahmad 22 Jeddah 4500 2
7 Salem 24 Riyadh 10000 2
Orders table
OID O_DATE CUSTOMER_ID AMOUNT
102 2009-10-08 3 3000
100 2009-10-08 3 1500
101 2009-11-20 2 1560
103 2008-05-20 NULL 2060
Equi join: An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows
that have equivalent values for the specified columns.
Example:
SELECT ID, NAME, OID, O_DATE
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
OR
SELECT CUSTOMERS.ID, CUSTOMERS.NAME, ORDERS.OID, ORDERS.O_DATE
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
OR
Using alias for the table names:
SELECT C.ID, C.NAME, O.OID, O.O_DATE
FROM CUSTOMERS C, ORDERS O
33
Diploma in Information Systems – Applied College Khamis Mushayt
Non equijoins: join condition containing something other than the equality operator.
SELECT C.ID, C.NAME, O.OID, O.O_DATE
FROM CUSTOMERS C, ORDERS O
WHERE O.O_DATE BETWEEN DATE '2009-10-08' AND DATE '2008-10-08';
Self join: is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases
that qualify column names in the join condition.
Examples:
1- Return a list of employees and their supervisors
34
Diploma in Information Systems – Applied College Khamis Mushayt
2- Return the ID, name and salary of customers who have salaries greater than Fahad.
35
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #11
Joins in SQL (continued)
Inner Join: (sometimes called a simple join) is a join of two or more tables that returns only those rows that satisfy
the join condition.
Outer join
It extends the result of a simple join. An outer join returns all rows that satisfy the join condition and also returns
some or all of those rows from one table for which no rows from the other satisfy the join condition.
36
Diploma in Information Systems – Applied College Khamis Mushayt
Left outer join: To write a query that performs an outer join of tables A and B and returns all rows from A (a left
outer join), use the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all
columns of B in the join condition in the WHERE clause. For all rows in A that have no matching rows in B, Oracle
Database returns null for any select list expressions containing columns of B.
Examples:
SELECT ID, NAME, OID, AMOUNT, O_DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
Note that: if we change the order of the tables in the from clause, then we will get different results.
SELECT ID, NAME, OID, AMOUNT, O_DATE
FROM ORDERS
LEFT JOIN Customers
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
37
Diploma in Information Systems – Applied College Khamis Mushayt
Right outer join: To write a query that performs an outer join of tables A and B and returns all rows from B (a
right outer join), use the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+)
to all columns of A in the join condition in the WHERE clause. For all rows in B that have no matching rows in A,
Oracle returns null for any select list expressions containing columns of A.
Examples:
SELECT ID, NAME, OID, AMOUNT, O_DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
The above statement is equivalent to:
SELECT ID, NAME, OID, AMOUNT, O_DATE
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID (+) = ORDERS.CUSTOMER_ID;
Full outer join: To write a query that performs an outer join and returns all rows from A and B, with nulls if they
do not satisfy the join condition (a full outer join), use the FULL [OUTER] JOIN syntax in the FROM clause.
38
Diploma in Information Systems – Applied College Khamis Mushayt
Examples:
SELECT ID, NAME, OID, AMOUNT, O_DATE
FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
39
Diploma in Information Systems – Applied College Khamis Mushayt
You can use UNION to return the result of a regular select statement and the result of join.
Examples:
SELECT NAME, ID AS CUSTOMERID FROM CUSTOMERS
UNION
SELECT NAME, CUSTOMER_ID FROM CUSTOMERS, ORDERS
WHERE ID = CUSTOMER_ID;
Note: UNION cannot be used to list ALL customer IDs from the two tables. Use UNION ALL to select duplicate
values.
Examples:
SELECT ID as CUSTOMERID FROM CUSTOMERS
UNION ALL
SELECT CUSTOMER_ID FROM ORDERS;
2- Intersection
The Oracle INTERSECT operator is used to return the results of 2 or more SELECT statements. However,
it only returns the rows selected by all queries or data sets. If a record exists in one query and not in the
other, it will be omitted from the INTERSECT results. Each SELECT statement within the INTERSECT
must have the same number of fields in the result sets with similar data types.
Examples:
SELECT ID AS CUSTOMERID FROM CUSTOMERS
INTERSECT
SELECT CUSTOMER_ID FROM ORDERS;
40
Diploma in Information Systems – Applied College Khamis Mushayt
You can use intersection to return the result of a regular select statement and the result of join.
Examples:
SELECT NAME, ID AS CUSTOMERID FROM CUSTOMERS
INTERSECT
SELECT NAME, CUSTOMER_ID FROM CUSTOMERS, ORDERS
WHERE ID=CUSTOMER_ID;
3- Minus
The Oracle MINUS operator is used to return all rows in the first SELECT statement that are not returned by the
second SELECT statement. Each SELECT statement will define a dataset. The MINUS operator will retrieve all
records from the first dataset and then remove from the results all records from the second dataset. Each SELECT
statement within the MINUS query must have the same number of fields in the result sets with similar data types.
Examples:
SELECT ID AS CUSTOMERID FROM CUSTOMERS
MINUS
SELECT CUSTOMER_ID FROM ORDERS;
You can use MINUS to return the result of a regular select statement and the result of join.
Examples:
SELECT NAME, ID AS CUSTOMERID FROM CUSTOMERS
MINUS
SELECT NAME, CUSTOMER_ID FROM CUSTOMERS, ORDERS
WHERE ID = CUSTOMER_ID;
41
Diploma in Information Systems – Applied College Khamis Mushayt
LAB #12
Introduction to PL/SQL
Aim: is to familiarize writing programs in PL/SQL language of Oracle.
Objectives: The objectives of this experiment are to:
1. Show the difference between PL/SQL and other programming language.
2. Give introduction to PL/SQL.
3. Write scripts in PL/SQL.
INTRODUCTION TO PL/SQL
PL/SQL stands for PROCEDURAL Language Extensions to SQL.
PL/SQL extends SQL by adding programming structures and subroutines available in any high level
language.
PL/SQL can be used for both server-side and Client side Development.
PL/SQL has syntax and rules that determine how programming statements work together.
PL/SQL is not a standalone Programming Language.
PL/SQL is a part of the ORACLE RDBMS and hence can reside in two environments, the CLIENT
and the SERVER.
Any MODULE that is developed using PL/SQL can be moved easily between SERVER SIDE and
CLIENT SIDE applications.
Either in CLIENT/SERVER environments any PL/SQL Block or the PL/SQL Engine processes
Subroutine.
PL/SQL Engine is a special component that processes and executes any PL/SQL statements and sends
any SQL statement to the SQL statement processor.
The SQL statement processes are always located on the ORACLE SERVER.
SERVER
CLIENT
When PL/SQL Engine is locted upon the SERVER,the whole PL/SQL block is passed to the PL/SQL
Engine on the ORACLE SERVER.
When the PL/SQL Engine is located upon the CLIENT,the PL/SQL processing is done on the
CLIENT SIDE.All SQL statenents that are embedded within the PL/SQL block,are sent to the
ORACLE SERVER for further processing.
If the PL/SQL block does not contain any SQL statements, the entire block is executed on the
CLIENT SIDE.
PL/SQL BLOCK
DECLARE
--Declarations of memory variables,constants,cursors etc.,in PL/SQL
BEGIN
--SQL executable statements
--PL/SQL executable statements
EXCEPTION
42
Diploma in Information Systems – Applied College Khamis Mushayt
/*SQL or PL/SQL code to handle errors that may arise during the execution of the code block between
BEGIN and EXCEPTION section
END;
Program 1: Simple PL/SQL script
BEGIN
dbms_output.put_line(‘ Marhaban Alf to PL/SQL ‘);
END;
Program 2: PL/SQL script to add two numbers
DECLARE
x number;
y number;
z number;
BEGIN
x:=10;
y:=20;
z:=x+y;
dbms_output.put_line(‘ z= ‘||z);
END;
Program 3: PL/SQL script to add two numbers – another way
DECLARE
x number:=10;
y number:=20;
z number;
BEGIN
z:=x+y;
dbms_output.put_line(‘ z= ‘||z);
END;
43
Diploma in Information Systems – Applied College Khamis Mushayt
END;
44
Diploma in Information Systems – Applied College Khamis Mushayt
x number:=&x;
y number:=&y;
BEGIN
IF (x=y) THEN
dbms_output.put_line(‘ Equal ‘);
ELSIF (x>y) THEN
dbms_output.put_line(x||‘ is Greater than ‘||y);
ELSE
dbms_output.put_line(x||‘ is less than ‘||y);
END IF;
END;
Exercises
Exercise 9.1: Write a PL/SQL script to print a given number entered thru keyboard is even or
odd.
Exercise 9.2: Write a PL/SQL script to demonstrate maximum among two numbers. Exercise
9.3: Write a PL/SQL script to demonstrate minimum among three numbers.
45
Diploma in Information Systems – Applied College Khamis Mushayt
LAB (optional)
PL/SQL Loops and Cursors
Aim: To write PL/SQL programs for extracting data from the database.
Objectives:The objectives of this experiment are to:
1. Embed SQL queries in PL/SQL.
1. Familiarize various types of loops in PL/SQL
2. Using cursor to get data from the database and display.
Program 1: Program to get employee name,job and salary from emp table.
declare
vename varchar2(20);
vjob varchar2(10);
vsal number(5);
begin
selectename,job,sal into vename,vjob,vsal from emp where empno=&eno;
dbms_output.put_line(‘Employee name=’||vename);
dbms_output.put_line(‘Employee job=’||vjob);
dbms_output.put_line(‘Employee Salary=’||vsal);
end;
Program 2: Program to get employee name,job and salary from emp table – when datatype of
variables are not known.
declare
venameemp.ename%type;
vjobemp.job%type;
vsalemp.sal%type;
begin
selectename,job,sal into vename,vjob,vsal from emp where empno=&eno;
dbms_output.put_line(‘Employee name=’||vename);
dbms_output.put_line(‘Employee job=’||vjob);
dbms_output.put_line(‘Employee Salary=’||vsal);
end;
46
Diploma in Information Systems – Applied College Khamis Mushayt
47
Diploma in Information Systems – Applied College Khamis Mushayt
Example Program:
BEGIN
fori in 1..5
LOOP
Dbms_output.put_line(‘i=’||i);
END LOOP;
END;
Program 3: PL/SQL program to get data (some rows) from the table and display on the screen
using cursor.
declare
cursor c1 is select * from emp;
d1emp%rowtype;
begin
open c1;
loop
fetch c1 into d1;
dbms_output.put_line(‘Employee name=’||d1.ename);
dbms_output.put_line(‘Employee job=’||d1.job);
dbms_output.put_line(‘Employee Salary=’||d1.sal);
end loop;
close c1;
end;
Program 4: PL/SQL program to get data (some rows) from the table using cursor for loop and
display on the screen.
declare
cursor c1 is select * from emp;
begin
fori in c1
loop
dbms_output.put_line(‘Employee name=’||i.ename);
dbms_output.put_line(‘Employee job=’||i.job);
dbms_output.put_line(‘Employee Salary=’||i.sal);
end loop;
end;
Note: for loop automatically declares, opens the cursor, fetch data from the cursor into i (of row
type),exits the loop and closes the cursor at the end.
Program 5:PL/SQL program to display employee name, job and salary from emp table whose
sal is greater than or equal to 2500
declare
cursor c1 is select * from emp where sal>=2500;
begin
fori in c1
loop
48
Diploma in Information Systems – Applied College Khamis Mushayt
dbms_output.put_line(‘Employee name=’||i.ename);
dbms_output.put_line(‘Employee job=’||i.job);
dbms_output.put_line(‘Employee Salary=’||i.sal);
end loop;
end;
Exercises
1. Write a PL/SQL script to find the factorial of a given number?
2. Write a PL/SQL script to display the employee name, job and salaries of employees
whose job is MANAGER;
3. Write a PL/SQL script to display the employees whose job is ANALYST and salary is
greater than or equal to 3000.
49
Diploma in Information Systems – Applied College Khamis Mushayt
LAB (optional)
PL/SQL Stored Procedures & Functions
Aim: To write PL/SQL stored procedures and functions.
Objectives: The objectives of this experiment are to:
1. Write stored procedures in PL/SQL.
2. Write stored functions in PL/SQL.
50
Diploma in Information Systems – Applied College Khamis Mushayt
BEGIN
C := A + B;
END;
Program 4:
CREATE OR REPLACE PROCEDURE DOUBLEN (N IN OUT INT) IS
BEGIN
N := N * 2;
END;
Execution: To run it, we also create a small code fragment:
DECLARE
R INT;
BEGIN
R := 7;
DBMS_OUTPUT.PUT_LINE(’BEFORE CALL R IS: ’ || R);
DOUBLEN(R);
DBMS_OUTPUT.PUT_LINE(’AFTER CALL R IS: ’ || R);
END;
Output:
BEFORE CALL R IS: 7
AFTER CALL R IS: 14
51
Diploma in Information Systems – Applied College Khamis Mushayt
Dropping a procedure:
DROP PROCEDURE procedure_name;
Example:
drop procedure doublen;
Stored Functions:
Output:
CUBE(6)
-----------
216
Program 2: PL/SQL function for calculating factorial of a number.
create or replace function fact(n number)return number
as
fac number:=1;
begin
for i in 1..n
loop
fac:=fac*i;
end loop;
return fac;
end;
/
Output:
SQL> select fact(5) from dual;
FACT(5)
----------
120
Dropping a function:
DROP FUNCTION function_name;
Example:
drop function fact;
52
Diploma in Information Systems – Applied College Khamis Mushayt
Exercises
Exercise 1: Write a PL/SQL procedure to calculate maximum among three numbers.
Exercise 2: Write a PL/SQL procedure to get the grade of a student when marks are passed thru the
procedure.
Exercise 3: Write a PL/SQL function to find the prime of a number passed thru the query.
53






![Diploma in Information Systems – Applied College Khamis Mushayt
7
Data type
description
VARCHAR2(size [BYTE |
CHAR])](https://screenshots.scribd.com/Scribd/252_100_85/326/668035533/7.jpeg)


