0% found this document useful (0 votes)
391 views53 pages

Database Management Systems Lab Guide

This document provides information about a database management systems lab course for Applied College Khamis Mushayt. It includes the course code, name, and coordinator. It outlines the 12 lab topics to be covered over the course, including introductions to Oracle, SQL, DDL, DML, constraints, queries, joins, and PL/SQL. It lists the software and references used. The first lab provides an introduction to Oracle and SQL data types.

Uploaded by

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

Database Management Systems Lab Guide

This document provides information about a database management systems lab course for Applied College Khamis Mushayt. It includes the course code, name, and coordinator. It outlines the 12 lab topics to be covered over the course, including introductions to Oracle, SQL, DDL, DML, constraints, queries, joins, and PL/SQL. It lists the software and references used. The first lab provides an introduction to Oracle and SQL data types.

Uploaded by

iTTi6.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • LAB #1: Introduction: Covers the basics of Oracle's history, SQL overview, and benefits of using Oracle as a database management system.
  • LAB #2: Basic Concepts and Types of SQL Commands: Discusses the fundamental types of SQL commands and provides practice exercises on DDL and DML commands.
  • LAB #3: DDL, DML and TCL Commands: Focuses on how to use Data Definition, Data Manipulation, and Transaction Control commands in SQL.
  • LAB #4: Database Constraints: Introduces various database constraints such as primary key, foreign key, unique, and not null constraints.
  • LAB #5: Database Constraints – Foreign Key (Continued): Continues with foreign key constraints detailing their use and implementation between tables.
  • LAB #6 & #7: Queries using Select Command and SQL Operators: Teaches how to build complex SQL queries using various operators, selection criteria, and logical operations.
  • LAB (Optional): Single Row SQL Functions: Covers different single row SQL functions including conversion, number, and date functions.
  • LAB #8 & #9: Aggregating Data and Using Group Functions: Discusses the use of aggregate functions and the application of group functions to manage data.
  • LAB #10: Joins in SQL: Explains different types of joins in SQL to retrieve data from multiple tables.
  • LAB #11: Joins in SQL (continued): Continues the exploration of SQL joins by diving into advanced join types such as inner, left, and right joins.
  • LAB #12: Introduction to PL/SQL: Introduces PL/SQL programming focusing on basic constructs and practices for writing codes in Oracle.
  • LAB (Optional): PL/SQL Loops and Cursors: Focuses on the use of loops and cursors within PL/SQL for data manipulation and retrieval.
  • LAB (Optional): PL/SQL Stored Procedures & Functions: Explores PL/SQL stored procedures and functions, demonstrating how to automate tasks within the database.
  • Exercises: Provides additional exercises and practice problems to reinforce understanding of PL/SQL topics covered.

Diploma in Information Systems – Applied College Khamis Mushayt

Lab manual

2422NAL Database System

Course Coordinator

Aftab Ahmed Abbasi

Department of Computer Science,


Program: Information Systems
Academic year-2022-2023

1
Diploma in Information Systems – Applied College Khamis Mushayt

Course Name Course Code


Database Management Systems 2 - LAB MIS332

Lab Syllabus with Work Plan


Lab No. Topics to be covered
LAB 1 Introduction to Oracle and SQL; What is SQL, Oracle data types.
LAB 2 Basic Concepts and Types of SQL commands
LAB 3 DDL, DML and TCL commands
LAB 4 Database Constraints (Primary key, check, not null, foreign key)
LAB 5 Database Constraints – Foreign Key (Continued)
LAB 6 Queries using select command and SQL operators
LAB 7 Queries using select command and SQL operators (Continued)
LAB 8 Aggregating Data and Group Functions
LAB 9 Aggregating Data and Group Functions (Continued)
LAB 10 Joins in SQL
LAB 11 Joins in SQL (continued)
LAB 12 Introduction to PL/SQL

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:

 MS SQL Server using T-SQL,


 Oracle using PL/SQL,
 MS Access version of SQL is called JET SQL (native format) etc.

Why SQL?

 Allows users to access data in relational database management systems.


 Allows users to describe the data.
 Allows users to define the data in database and manipulate that data.
 Allows to embed within other languages using SQL modules, libraries & pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a database.
 Allows users to set permissions on tables, procedures and views

SQL History:

 1970 -- Dr. E. F. "Ted" of IBM is known as the father of relational databases. He


described a relational model for databases.
 1974 -- Structured Query Language appeared.
 1978 -- IBM worked to develop Codd's ideas and released a product named System/R.
 1986 -- IBM developed the first prototype of relational database and standardized by
ANSI. The first relational database was released by Relational Software and its later
becoming Oracle.

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.

Following is a simple diagram showing SQL Architecture:

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:

Data Definition Language (DDL):


Command Description
CREATE Creates a new table, a view of a table, or other object in database
ALTER Modifies an existing database object, such as a table.
DROP Deletes an entire table, a view of a table or other object in the database.

5
Diploma in Information Systems – Applied College Khamis Mushayt

Data Manipulation Language (DML):


Command Description
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records

Data Query Language (DQL):


Command Description
SELECT Retrieves certain records from one or more tables

Data Control Language (DCL):


Command Description
GRANT Gives a privilege to user
REVOKE Takes back privileges granted from user

Transaction Control Language (TCL):


Command Description
COMMIT save work done
SAVEPOINT identify a point in a transaction to which you can later roll back
ROLLBACK restore database to original since the last COMMIT

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.

Oracle data types


Each value manipulated by Oracle Database has a data type. The data type of a value associates a
fixed set of properties with the value. These properties cause Oracle to treat values of one data
type differently from values of another. Oracle Database provides a number of built-in data types
as well as several categories for user-defined types that can be used as data types. The syntax of
built-in oracle data types appears in the following table:

6
Diploma in Information Systems – Applied College Khamis Mushayt

Data type description


Variable-length character string having maximum length size
bytes or characters. Maximum size is 4000 bytes or characters,
and minimum is 1 byte or 1 character. You must specify size
for
VARCHAR2.
BYTE indicates that the column will have byte length
semantics. CHAR indicates that the column will have character
semantics.
VARCHAR2(size [BYTE |
For example, if you define the field as VARCHAR2(11 BYTE),
CHAR])
Oracle can use up to 11 bytes for storage, but you may not
actually be able to store 11 characters in the field, because some
of them take more than one byte to store, e.g. non-English
characters. By defining the field as VARCHAR2(11
CHAR) you tell Oracle it can use enough space to store 11
characters, no matter how many bytes it takes to store each one.
A single character may require up to 4 bytes.

Fixed-length character data of length size bytes or characters.


Maximum size is 2000 bytes or characters. Default and
CHAR [(size [BYTE |
minimum size is 1 byte.
CHAR])]
BYTE and CHAR have the same semantics as for
VARCHAR2.
Character data of variable length up to 2 gigabytes, or 231 -
LONG
1bytes. Provided for backward compatibility.
Number having precision p and scale s. The precision p can
range from 1 to 38. The scale s can range from -84 to 127. Both
precision and scale are in decimal digits. A NUMBER value
requires from 1 to 22 bytes. To better understand precision and
scale in NUMBER data type, we can apply the following rule:
NUMBER [ (p [, s]) ] NUMBER (LEFT + RIGHT, RIGHT)
That is, NUMBER (3, 2) can hold a number having 2 or less
digits on the right of the decimal, and consequently up to [3-2=]
1 digit on the left of the decimal.
So a NUMBER (3, 2) variable can hold no value greater than
9.99.
A subtype of the NUMBER data type having precision p. A
FLOAT value is represented internally as NUMBER. The
FLOAT [(p)]
precision p can range from 1 to 126 binary digits. A FLOAT
value requires from 1 to 22 bytes.
Valid date range from January 1, 4712 BC, to December 31,
9999 AD. The default format is determined explicitly by the
DATE NLS_ DATE_FORMAT parameter or implicitly by the
NLS_TERRITORY parameter. The size is fixed at 7 bytes. This
data type contains the datetime fields YEAR, MONTH, DAY,

7
Diploma in Information Systems – Applied College Khamis Mushayt

HOUR, MINUTE, and SECOND. It does not have fractional


seconds or a time zone.
Year, month, and day values of date, as well as hour, minute,
and second values of time, where fractional_seconds_precision
is the number of digits in the fractional part of the SECOND
datetime field. Accepted values of
fractional_seconds_precision are 0 to 9. The default is 6. The
TIMESTAMP
default format is determined explicitly by the
[(fractional_seconds_
NLS_TIMESTAMP_FORMAT parameter or implicitly by the
precision)]
NLS_TERRITORY parameter. The size is 7 or 11 bytes,
depending on the precision. This data type contains the
datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and
SECOND. It contains fractional seconds but does not have a
time zone.

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

univno name course m1 m2 m3 total

1. create command example:


create table student
( univno number(9),
name varchar2(50),
course char(3),
m1 number(3),
m2 number(3),
m3 number(3),
total number(3));

2. To see the structure of the table

desc student

3. Insert data into the table:


insert into student values(432820234,’Saeed’,’CE’,100,100,100,0);

 insert at least three students

4. View the data contents of the table


select * from student;
5. To save the data of the table permanently:
commit:

9
Diploma in Information Systems – Applied College Khamis Mushayt

Exercise
Exercise 1.1: Practice all the above commands with the course table given below.

courseno cname crhr days Time


CPE210 DBMS 3 13 10:00-10:50AM

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.

univno name course m1 m2 m3 total

DDL commands:
1. To delete or drop a table ( if exists )
drop table student;

2. Create command example:


create table student
( univno number(9),
name varchar2(50),
course char(3),
m1 number(3),
m2 number(3),
m3 number(3),
total number(3));

3. Add a new column to the table


alter table student add avg number(5,2);

4. To increase the size of the column


alter table student modify avg number(6,2);

5. To see the structure of the table

desc student;

11
Diploma in Information Systems – Applied College Khamis Mushayt

DML and TCL commands:

6. Insert data into the table:


insert into student values(432820234,’Saeed’,’CE’,100,100,100,0);

insert at least three students.

7. To update the total column.


update student set total=m1+m2+m3;

8. View the data contents of the table.


select * from student;

9. To save the data of the table permanently:


commit:

10. Insert once again some student:


insert into student values(432820237,’Majid’,’CE’,100,95,98,0);

11. Practice rollback command:


rollback;
i) After the rollback the above student 432820237 will be deleted.
ii) Execute the update command again and commit to save.

12. To delete all the students.


delete from student;

13. Undelete the data using rollback again.


rollback;

14. To delete a single or particular record:


delete from student where univno=432820123;

15. Update avg column of the table


update student set avg=total/3;

16. To change the name of m3 to final


Alter table student rename column m3 to final;

17. To delete a column from the table


alter table student drop column avg;

18. To see the structure of the table

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.

courseno Cname crhr days time


CPE210 DBMS 3 13 10:00 - 10:50 AM
CPE122 OOP 3 24 09:00 – 09:50 AM
CPE220 Microprocessors 3 13 11:00 – 11:50 AM

Exercise 2.2: Practice all the above commands for the emp table given below.

Empno ename Job mgr sal overtime total


1111 Majid MANAGER 12000 500 12500
2222 Saad ANALYST 1111 10000 500 10500
3333 Tamer CLERK 2222 5000 300 5300

(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;

4. Create the table with constraints.


create table student
( univno number(9) primary key,
name varchar2(50) not null,
idno number(10) not null unique,
course char(3) not null,
m1 number(3) not null check(m1 between 0 and 100),
m3 number(3) not null ,
total number(3) not null check(total >=0 and total between 0 and 300));

5. To see the structure of the table


desc student

6. Insert data into the table:


insert into student values(432820234,’Saeed’,1084567867,’CE’,100,100,100,0);

-insert at least three students

7. To see the data in the table:


select * from student;

6. To save the data of the table permanently:


commit:

7. To update the total column


update student set total=m1+m2+m3;

8. To add a new column to the student table:


alter table student add avg number(5,2);

9. To update the avg column:

15
Diploma in Information Systems – Applied College Khamis Mushayt

update student set avg=total/3;

10. To remove one column from the table


alter table drop column avg;

11. To change the name of a student:


update student set name=’Ali’ where univno=432820234;

12. To change the marks of the student:


update student set m1=100 where univno=432820234;

13. To add a new column along with check constraints


alter table student add m2 number check (m2>2);

14. To add check constraints to m3


Alter table student add constraint check_m3 check (m3 between 1 and 100);

15. To drop check constraints of m3


Alter table student drop constraints check_m3;

Exercises
Exercise 3.1: Practice all the above commands with four constraints on the course table
given below:

courseno Cname crhr days time


CPE210 DBMS 3 13 10:00 - 10:50 AM
CPE122 OOP 3 24 09:00 – 09:50 AM
CPE220 Microprocessors 3 13 11:00 – 11:50 AM

Exercise 3.2: Practice all the above commands with the emp table given below.

Empno ename idno job Sal overtime deptno


1111 MAJID 1081025674 CEO 50000 10
2222 SAAD 1084567890 MANAGER 40000 20

16
Diploma in Information Systems – Applied College Khamis Mushayt

LAB #5
Database Constraints – Foreign Key (Continued)

Aim: Apply foreign key between the two tables.


Objectives:
1. Review the various types of database constraints.
2. Familiarize how to use foreign key constraint.
3. Apply foreign key constraint between the two tables.
Description:
e. Foreign Key: A key applied on detail/derived table whose primary key is in
the master/base table.

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

How to create the relationship:


Steps:
1. First create the master (parent) table dep:
create table dep ( dno number(2) primary key, dname varchar2(40) not null, loc
varchar2(20) not null);

2. Create the detail (child) table employee:


create table employee (
empno number(4) primary key,
dno number(2) [not null]
ename varchar2(50) not null,
job varchar2(20) not null,
mgr number(4) ,
sal number(7,2) not null,
comm number(6,2),
Foreign key (dno) references dep(dno));
3. Repeat the steps given in earlier weeks and apply the DDL and DML commands on
the above master-detail table.

1. To see the structure of the table

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);

insert into employee values


(1112,10,’Saeed’,‘Professor’,1111,5000,null);

18
Diploma in Information Systems – Applied College Khamis Mushayt

insert into employee values


(1113,30,’Majid’,‘Secretary’,1111,3000,500);

4. Check the data in dep table:


select * from dep;

5. Check the data in employee table:


select * from employee;

6. To save the data of the table permanently:


Commit;

7. To add primary key constraints


ALTER TABLE employee ADD constraint PK_dno PRIMARY KEY (dno);

8. To drop primary key constraints


ALTER TABLE employee drop constraint PK_dno;

9. To add foreign key constraints


ALTER TABLE employee ADD CONSTRAINT fk_dno FOREIGN KEY (dno)
REFERENCES dept(dno);

10. To drop foreign key constraints


ALTER TABLE products DROP CONSTRAINT fk_dno;

** 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:

Babano Babaname idno


1 MAJID 1084567890
2 SAJID 1086673409

Babano Bno Bname idno mobileno


1 1 ALI 1089456735 0508765436
1 2 SAAD 1087893434 0508765738
2 1 SAEED 1086785433 0508882345

Exercise 4.2: Practice the same as above on the following two teacher and course tables
given below:

Teacherno Teachername officeno

courseno coursename crhr day Teacherno

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

Arithmetic Meaning Comparison Meaning


Operators Operators
+ Addition < Less than
- Subtraction > Greater than
* Multiplication <= Less than or
equal
/ Division >= Greater than
or equal
= Equal to
!= or <> Not equal to

Logical Operators
and
or
not

Other operators Meaning


[NOT] between range of values (numeric or 'text' ) both inclusive
[NOT] like Match character pattern
[NOT] in Match a list of values
Compares a value to each value in a list or returned by a
query. Must be preceded by =, !=, >, <, <=, or >=. Evaluates
Some/any
to FALSE if the query returns no rows. (joins many OR
operators).
Compares a value with every value in a list or returned by a
query. Must be preceded by =, !=, >, <, <=, or >=. Evaluates
All
to TRUE if the query returns no rows. (joins many AND
operators).

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.

Use the following table (emp) to complete examples:

empno ename Job Sal City Increase_percentage


1 Ahmad manager 2000 Abha 10%
2 Nasser secretary 4000 Jeddah 20%
3 Ali salesman 20000 Abha 10%
4 Fahad salesman null Najran 25%

1) Use of Arithmetic Operators in select:

i) select empno,ename,sal from emp;


ii) select empno,ename,sal, sal+500 from emp;
iii) select empno,ename,sal, sal*2 from emp;
iv) select empno,ename,sal, sal+(sal+40*sal/100) from emp;

2) Use of Comparison Operators in select and use of where clause:


i) select * from emp where sal<1000;
ii) select * from emp where sal>1000;
iii) select * from emp where sal<=3000;
iv) select * from emp where sal>=3000;
v) select * from emp where sal!=5000;
vi) select * from emp where sal=3000;

3) Use of logical operators:


i) select * from emp where job=’MANAGER’ and sal>=3000;
ii) select * from emp where job=’MANAGER’ or sal>=3000;
iii) select * from emp where job=’SALESMAN’ and not sal>=3000;

4) Use of Other operators using select:

i) select * from emp where sal between 1000 and 3000;

22
Diploma in Information Systems – Applied College Khamis Mushayt

ii) select * from emp where ename like ‘N%’;


iii) select * from emp where ename like ‘_hmad’;
iv) select * from emp where sal in (2000,1250,4000);
v) select * from emp where sal > any (2000,4000);
vi) select * from emp where sal > all (2000,4000);
vii) select * from emp where sal is null;

5) To update the salary in the table:

i) To update all the employees salary by 40%.

update emp set sal=sal+sal*40/100;

ii) To update a particular employee salary by 40%.

update emp set sal=sal+sal*40/100 where empno=7639;


Exercises
Exercise 5.1: Give the various select commands for using arithmetic, logical and relational
operators with different values.
Exercise 5.2: Give the select command for the following queries
i) List all the employees whose job is MANAGER and salary equal to 3000.
ii) List all the employees whose salary is greater than or equal to 3000.
iii) Update the salary of employees by 30% whose job is SALESMAN in the emp table.

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.

There are two types of functions in SQL:


i) Single row functions
ii) Multi row functions
In the single row functions there are of five types:
1) General functions
2) Character functions
3) Number functions
4) Date functions
5) Conversion functions

1) General functions: Some of the functions are:

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

when ‘MANAGER’ then sal*50/100


else sal
end
from emp;

2) Character functions: there are two types of character functions


a) Case manipulation functions
i) lower
Example: SELECT LOWER(‘DBMS’)FROM DUAL;
ii) upper
Example: SELECT UPPER(‘dbms’) FROM DUAL;
iii) initcap
Example: SELECT INITCAP(‘dbms’)FROM DUAL;
b) Character manipulation functions
i) concat
Example: select concat(‘Marhaban’,’Alf’) from dual;
ii)substr
Example: select substr (‘Marhaba’,2,5)) from dual;
iii) length
Example: select length (‘Marhaba’) from dual;
iv) lpad and rpad
Example: select lpad (1200,6,’*’) from dual;
select rpad (1200,6,’*’) from dual;
use of lpad and rpad both sides:
select lpad(rpad(1200,6,’*’),8,’*’) from dual;
v) trim
select trim(‘M’ from ‘Marhaban Alf’) from dual;
vi) replace
select replace (‘Marhaban alf’,’alf’,’Million’) from dual;
3) Number functions
i) round
Example: select round(12.36) from dual;
select round(12.5) from dual;

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:

SELECT MONTHS_BETWEEN (TO_DATE(SYSDATE,’DD-MON-YYYY’),


TO_DATE(’25-OCT-1990’,’DD-MON-YYYY’))/12 FROM DUAL;
iii) to_number
Examples: select to_number(‘123’) from dual;

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;

e. Count has three formats:


i. count(*) ; returns the number of rows in a table
Example: select count (*) from emp;
ii. count (expr) ; returns the number of rows with non-null values. Identified by
expr.
Example: select count (comm) 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;

Comparison over Aggregation


Aggregation cannot appear directly in where clause. For example, for this query "Return the
name of employee with highest salary", we can NOT use the following select statement:
Select ename from emp where sal = max (sal).
Because the max function can be computed only after seeing all rows in the table, but when
executing where clause, we can see one row in the table.
We use subquery to address this problem.
Select ename From emp Where sal = (select max(sal) from emp);
In this case, the subquery will be processed first.
Creating Groups of Data:
Divide rows in the table into smaller groups by using group by clause.
1- Using group by clause:
i) All columns in the select list that are not in group functions must be in group by
clause.
Examples:
select job, sum(sal) from emp group by job;
select city, sum(sal),avg(sal),max(sal),min(sal) from emp group by city;

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

2- Using group by clause for multiple columns:


Example: select city, job, sum(sal), avg(sal), max(sal), min(sal) from emp group by
city, job;

3- Excluding group results: having clause


Use the having clause to restrict groups
i) Rows are grouped
ii) Group function is applied
iii) Groups matching the having clause are displayed
Example:
select city, max(sal) from emp group by city having max(sal)>1000;
select job, sum(sal) from emp group by job having sum(sal)>1000 order by
sum(sal);

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.

Access data from multiple tables:


Cartesian product: Oracle combines each row of one table with each row of the other. A
Cartesian product always generates many rows and is rarely useful. For example, the Cartesian
product of two tables, each with 100 rows, has 10,000 rows. It is formed when:

a. A join condition is omitted


b. A join condition is invalid
Note: To avoid Cartesian product always include a valid join condition in a where clause. To do
so, you need to apply the following steps:
 Decide the set of tables involved.
- Locate columns being returned.
- If these columns are from multiple tables, select those tables that contain these
columns and all tables that link these tables together.
 Put those tables in the from clause.
 Add one join condition for each key-foreign link in these tables (in addition to other
required conditions).
- Typically if there are k tables involved, add k-1 join conditions in the where
clause.

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

WHERE C.ID = O.CUSTOMER_ID;

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

SELECT C1.ID AS CUSTOMER_ID, C1.NAME AS CUSTOMER_NMAE,


C2.ID AS SUPERVISOR_ID, C2.NAME AS SUPERVISOR_NAME
FROM CUSTOMERS C1, CUSTOMERS C2
WHERE C1.SUPERVISOR_ID = C2.ID;

34
Diploma in Information Systems – Applied College Khamis Mushayt

2- Return the ID, name and salary of customers who have salaries greater than Fahad.

SELECT C2.ID, C2.NAME, C2.SALARY


FROM CUSTOMERS C1, CUSTOMERS C2
WHERE C1.name='Fahad'
AND C2.SALARY > C1.SALARY;

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.

SELECT ID, NAME, AMOUNT, O_DATE


FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

The above statement is equivalent to:


SELECT ID, NAME, AMOUNT, O_DATE
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Equijoin Vs. Inner join


Almost every join is an equijoin, because the condition for matching rows is based on the equality of two values—
one from each of the tables being joined. So that's what makes it an equijoin: the ON condition is equality. This
includes inner joins and all three types of outer joins.
Inner joins, on the other hand, can be based on equality to match rows, or on some other condition entirely.

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;

The above statement is equivalent to:

SELECT ID, NAME, OID, AMOUNT, O_DATE


FROM CUSTOMERS, ORDERS
WHERE 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;

In addition three more operations are:


1- Union
The Oracle UNION operator is used to combine the result sets of 2 or more Oracle SELECT statements. It removes
duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must
have the same number of fields in the result sets with similar data types.
Examples:
SELECT ID as CUSTOMERID FROM CUSTOMERS
UNION
SELECT CUSTOMER_ID FROM ORDERS;

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.

As per the necessity the PL/SQL Engine can be located either at

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;

Program 4: PL/SQL script to add two numbers – using keyboard input


DECLARE
x number:=&x;
y number:=&y;
z number;
BEGIN
z:=x+y;
dbms_output.put_line(‘ z= ‘||z);
END;

43
Diploma in Information Systems – Applied College Khamis Mushayt

Program 5: PL/SQL script about for Simple IF


DECLARE
x number:=&x;
y number:=&y;
BEGIN
IF (x=y) THEN
dbms_output.put_line(‘ Equal ‘);
END IF;
END;

Program 6: PL/SQL script about for IF .. ELSE statement


DECLARE
x number:=&x;
BEGIN
IF (x>0) THEN
dbms_output.put_line(‘ Positive number ‘);
ELSE
dbms_output.put_line(‘ Negative number ‘);
END IF;

END;

Program 7: PL/SQL script about for Nested IF .. ELSE statement


DECLARE
x number:=&x;
y number:=&y;
BEGIN
IF (x=y) THEN
dbms_output.put_line(‘ Equal ‘);
ELSE IF (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 IF;
END;
OR
Same Program using IF … ELSIF ….ELSE
DECLARE

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

There are three types of loops:


i) loop
Syntax:
LOOP
statement1;
EXIT [ WHEN Condition];
END LOOP;
Example Program:
DECLARE
i number:=1;
BEGIN
LOOP
Dbms_output.put_line(‘i=’||i);
i:=i+1;
EXIT WHEN (i>5);
END LOOP;
END;

ii) while loop


Syntax:
WHILE condition LOOP
statement1;
statement2;
END LOOP;
Example Program:
DECLARE
i number:=1;
BEGIN
WHILE(i<=5)
LOOP
Dbms_output.put_line(‘i=’||i);
i:=i+1;
END LOOP;
END;

iii) for loop


Syntax:
FOR counter IN [REVERSE]
LowerBound..UpperBound
LOOP
statement1;
statement2;
END LOOP;

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.

General format for stored procedures:


CREATE OR REPLACE PROCEDURE procedure_name ( parameters ) IS
BEGIN
procedure_body
END;
Program 1:
CREATE OR REPLACE PROCEDURE DISPN (N INT) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(’N is ’ || N);
END;
Program 2:
CREATE OR REPLACE PROCEDURE DISP_AB (A INT, B INT) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(’A + B = ’ || (A + B));
DBMS_OUTPUT.PUT_LINE(’A * B = ’ || (A * B));
END;
Execution:
CALL DISP_AB(17,23);
A + B = 40
A * B = 391
Program 3:
CREATE OR REPLACE PROCEDURE SUM_AB (A INT, B INT, C OUT INT) IS

50
Diploma in Information Systems – Applied College Khamis Mushayt

BEGIN
C := A + B;
END;

Execution: Write the following program to run the procedure


DECLARE
R INT;
BEGIN
SUM_AB(23,29,R);
DBMS_OUTPUT.PUT_LINE(’SUM IS: ’ || R);
END;
Output:
SUM IS: 52

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:

Program 5: PL/SQL function for calculating cube of a number.


create or replace function mycube (n number) return number
as
c number;
begin
c:=n*n*n;
return c;
end;
/
Execution:
SQL> select mycube(6)from dual;

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 
1 
 
 
 
 
 
Lab manual 
 
 
 
 
 
 
2422NAL  Database Syste
Diploma in Information Systems – Applied College Khamis Mushayt 
2 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Course Name
Diploma in Information Systems – Applied College Khamis Mushayt 
3 
 
LAB #1 
Introduction 
ORACLE 
 
It is a very large and
Diploma in Information Systems – Applied College Khamis Mushayt 
4 
 
 Data Warehousing  
 Materialized views  
 Bitmap in
Diploma in Information Systems – Applied College Khamis Mushayt 
5 
 
SQL Process: 
 
When you are executing an SQL command f
Diploma in Information Systems – Applied College Khamis Mushayt 
6 
 
Data Manipulation Language (DML): 
Description  
Comman
Diploma in Information Systems – Applied College Khamis Mushayt 
7 
 
 
Data type 
description 
VARCHAR2(size [BYTE | 
CHAR])
Diploma in Information Systems – Applied College Khamis Mushayt 
8 
 
HOUR, MINUTE, and SECOND. It does not have fractional
Diploma in Information Systems – Applied College Khamis Mushayt 
9 
 
 
LAB #2 
Basic Concepts and Types of SQL commands 
Aim
Diploma in Information Systems – Applied College Khamis Mushayt 
10 
 
 
 
 
 
 
 
Exercise 
 
Exercise 1.1: Practice all the

You might also like