Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

231 - CIS - Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬

Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

231-CIS-3
Database Management System
Department of Information systems
College of Computer Science
King Khalid University

(Lab Manual)
Semester I (2021)

231-CIS-3 | Lab Manual 1


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Course Name Course Code


Database Management Systems - LAB 231CIS

Lab Syllabus with Work Plan


No. of
Lab No. Topics to be covered
Weeks
Introduction to Oracle Environment and its installation and exploring database tables and
LAB 1 2
manual retrieval of data
LAB 2 Practice exercise on relational algebra 1
LAB 3 SQL: Oracle data types, Creating, Updating and Deleting Schema and Records (CREATE,
2
INSERT, UPDATE, ALTER, DELTE, DROP), Integrity Constraints
LAB 4 SQL: Querying databases (SELECT, WHERE, LIKE, IN, AND/OR/NOT, ORDER BY) 1
LAB 5 SQL: Querying Database (Aggregation, Group By, Having) 2
LAB 6 SQL: Querying Database (Joins, Views) 2
LAB 7 SQL: Functions, Stored Procedures, Triggers 2
LAB 8 Developing ER diagram using MS Visio (or any alternative) 1
LAB 9 Application development using Oracle Form Developer 2

Software(s)/Tools Used§
Oracle 18c 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
-Oracle PL/SQL by Example 5th Edition, Benjamin Rosenzweig, Elena Rakhimov, 2015
ISBN-13: 978-0133796780

231-CIS-3 | Lab Manual 2


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Introduction to Oracle Environment and its installation and exploring


LAB-1
database tables and manual retrieval of data

This lab teaches the following topics:


• Introduction to Oracle.
• What’s SQL and its architecture?
• Steps to download Oracle XE and sql developer
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.

Features:
• Concurrency
• Read Consistency
• Locking Mechanisms
• Quiescent Database
• Data Warehousing

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:
• 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.
231-CIS-3 | Lab Manual 3
College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

• 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 view, stored procedure, functions in a database.
• Allows users to set permissions on tables, procedures and views

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:

231-CIS-3 | Lab Manual 4


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

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.

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

231-CIS-3 | Lab Manual 5


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Steps to download Oracle XE and sql developer


• Go to https://www.oracle.com/database/technologies/xe-downloads.html
• Download the file named “Oracle Database 18c Express Edition for Windows x64”

● Save file prompt will pop up to choose the directory where the file will be downloaded
● Locate the file in your system


● Right-click on the .zip file and choose Extract All

231-CIS-3 | Lab Manual 6


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

● Click Extract

Steps to Install Oracle XE


● Inside the extracted folder, locate the installation package named “setup” and double click on it


● Follow the following screenshots until the installation is successfully completed

1 2 3

4 8
5

6 7

● Now, the installation process has begun, and you should wait until the progress bar finish.
● After the installation finishes, a window with user and connection setting will show up. Please take a
note of the information as you may need it later to setup a connection to the database, then click “finish”

231-CIS-3 | Lab Manual 7


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Now, you have successfully downloaded and installed Oracle XE on your system.

Steps to download and install SQL Developer


● Go to https://www.oracle.com/tools/downloads/sqldev-downloads.html
● Download the file named “Windows 64-bit with JDK 8 included”


● Save file prompt will pop up to choose the directory where the file will be downloaded
● Locate the file in your system, right-click and choose “Extract All”, then “Extract”


● Locate the extracted folder “sqldeveloper-20.2.0.175.1842-x64” and right-click on it, then choose “Cut”

231-CIS-3 | Lab Manual 8


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

● Go to and paste the folder inside this directory.

● Go inside the folder and right-click on the application named “sqldeveloper” and choose “create
shortcut”

● Move the shortcut to Desktop for easy access

231-CIS-3 | Lab Manual 9


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

LAB-2 Practice Exercise on Relational Algebra

This lab teaches the following topics:


• How to formulate a variety of relational algebra to express a broad range of query problems.
• including select, project and Cartesian product, assignment and other operators
• How to composite of relational operations using AND, OR and NOT.
• How to apply set operators on a relations
• How to differentiate among the results of set operators
Prerequisites
• Review the given theoretical lectures of Relational Algebra.
• Use MS word to type practice making Relational Algebra or simply use a pen and white sheet.
Learning resources
All activates are collected from Chapter 2, the textbox: Database System Concepts, Seventh Edition, Avi
Silberschatz, Henry F. Korth, S. Sudarshan, McGraw-Hill, ISBN 9780078022159 (February, 2019)

Session Activates
With the help of Figure 3.1, read each activity from A to G carefully and give an expression in the relational
algebra to express each of the following queries

Figure 3.1 : Schema of the university database.

A) The Select Operation(δ)


Based on 'instructor' relation, do the following:
1. Retrieve all tuples where the department name should be ' Physics'.
Answer: δ dept name =“Physics” (instructor)

231-CIS-3 | Lab Manual 10


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

2. Find all instructors whose salary greater than $50,000.


Answer : δ salary >50000 (instructor)

3. Now retrieve all instructors whose salary greater than $50,000 and work at Physics department
Answer: δ salary >50000 ˄dept name =“Physics” (instructor)

B) The Project Operation(π)


1. Retrieve only these attributes: section id , course id and building form the relation 'section'.
Answer: π sec_id, course_id, building(section)

C) The Assignment Operation (ß)


1. Now, assign the result of previous Activity B to R.
Answer: R ßπ sec_id, course_id, building(section)

D) Composition of Relational Operations using AND OR


1. Based on the relation 'instructor', find out id, name and salary for all instructors whose salary greater
than $10,000 or work at Physics department
Answer: to simplify the solution, we will divide the relational algebra into 2 steps according to the
requirements of the given exercise.
o Step1: find selection first to improve the performance and save the result as R.
Rß δ salary >10000 V dept name =“Physics” (instructor)
o Step2: find the projection as :
π id, name, salary (R)

Note: this solution is equivalent to :


π id, name, salary (salary >10000 V dept name =“Physics” (instructor)).

231-CIS-3 | Lab Manual 11


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

E) The Cartesian-Product Operation (X)


Consider two relations: student(id, fname, lname) and department (dept_name, building) below:
id fname lname dept_name building
11111 Ali Ahmed Information Systems A
23222 Nora Khalid Networking B

1. Now, apply Cartesian-Product on student and department:


answer: apply student ✕ department to get the following result.
id fname lname dept_name building
11111 ali ahmed information systems a
11111 ali ahmed networking b
23222 nora khalid information systems a
23222 nora khalid networking b

2. How many tuples have been resulted after performing Cartesian Product on the given relations, and
also how many attributes
Answers:
No. of tuples = no. of student's tuples * no. of department's tuples
= 2*2 = 4 tuples
No. of attributes = no. of student's attributes + no. of department's attributes
= 2+3 = 5 attributes.

231-CIS-3 | Lab Manual 12


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

F) The Join Operation


1. Using relations: instructor and teaches to find the information about all instructors together with the
course id of all courses they have taught.
Answer:
o Step1: apply the Cartesian product on the given relations as instructor × teaches to give you
the below results.

Table 3.1: the result of instructor × teaches

o Step2: Since the Cartesian-product operation associates every tuple of instructor with every
tuple of teaches, we know that if an instructor has taught a course (as recorded in the teaches
relation), then there is some tuple in instructor × teaches that contains her name and satisfies
instructor.ID = teaches.ID.

So, by applying join on step1 as σinstructor.ID=teaches.ID(instructor × teaches), we get only those tuples of instructor
× teaches that pertain to instructors and the courses that they taught.

231-CIS-3 | Lab Manual 13


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

G) Set Operations ( union – intersection – self-subtraction)


Study the information of the section relation as shown in the next table and use the appropriate set operator
to answer the following:

Table 3.2: the information of the section relation

1) Consider a query to find the set of all courses taught in the Fall 2017 semester and then assign the
result to 'Course_id_fall_2017'.

Answer: Course_id_fall_2017ßπcourse_id (δsemester =“Fall”∧ year=2017 (section))

2) Consider a query to find the set of all courses taught in the Spring 2018 semester and then assign the
result to 'Course_id_spring_2018'.

Answer: Course_id_spring_2018ßπcourse_id (δsemester =“Spring”∧ year=2018 (section))

3) Now consider a query to find the set of all courses taught in the Fall 2017 semester or the Spring 2018
semester. Then assign the result to 'Course_id_union'

Answer: apply the interstation operation on step1 and step2 if applicable to get: Course_id_union
Course_id_fall_2017 U Course_id_spring_2018

4) Suppose that we wish to find the set of all courses taught in both the Fall 2017 and the Spring 2018
semesters.

Answer: apply the interstation operation on step1 and step2 if applicable to get: Course_id_intersection
Course_id_fall_2017 ∧ Course_id_spring_2018

231-CIS-3 | Lab Manual 14


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

5) Finally, find all the courses taught in the Fall 2017 semester but not in Spring 2018 semester.

Answer: apply set-difference operation on step1 and step2 if applicable to get:


Course_id_intersection Course_id_fall_2017 - Course_id_spring_2018

Self-Practice Exercises
Practice the following exercises alone and then try compare your answers with your classmates.

Activity 1: What is the result of first performing the Cartesian product of student and advisor, and then
performing a selection operation on the result with the predicate s id = ID? (Using the symbolic notation of
relational algebra, this query can be written as σs_id=ID(student × advisor).

Activity 2: Consider the employee database of Figure 2.2. Give an expression in the relational algebra to
express each of the following queries:
• Find the ID and name of each employee who does not work for “BigBank”.
• Find the ID, name, and city of residence of each employee who works for “BigBank”.
• Find the ID, name, street address, and city of residence of each employee who works for “BigBank” and
earns more than $10000.
• Find the ID and name of each employee in this database who lives in the same city as the company for
which she or he works
• Find the ID and name of each employee who earns at least as much as every employee in the database.

Figure 3.2 : Employee database

231-CIS-3 | Lab Manual 15


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Activity 3: Consider the bank database of Figure 2.3. Give an expression in the relational algebra for each of
the following queries:
• Find the name of each branch located in “Chicago”.
• Find the ID of each borrower who has a loan in branch “Downtown”
• Find each loan number with a loan amount greater than $10000.
• Find the ID of each depositor who has an account with a balance greater than $6000.
• Find the ID of each depositor who has an account with a balance greater than $6000 at the “Uptown”
branch.

.
Figure 2.3 : Bank database

231-CIS-3 | Lab Manual 16


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

SQL: Oracle data types, Creating, Updating and Deleting Schema and Records
LAB-3
(CREATE, INSERT, UPDATE, ALTER, DELTE, DROP), Integrity Constraints

This lab teaches the following topics:


• Oracle data types.
• Practice DDL to create, modify or drop a given table.
• Practice DML commands to insert, update, and delete the data.
• Practice TCL commands to commit or rollback the data in the table.
• Types of database constraints (primary key, not Null, check, foreign key)
Oracle data types
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), Oracle can use up to 11
CHAR])
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
CHAR [(size [BYTE |
2000 bytes or characters. Default and minimum size is 1 byte.
CHAR])]
BYTE and CHAR have the same semantics as for VARCHAR2.
LONG Character data of variable length up to 2 gigabytes, or 231 -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
FLOAT [(p)] represented internally as NUMBER. The precision p can range from 1 to 126 binary
digits. A FLOAT value requires from 1 to 22 bytes.

231-CIS-3 | Lab Manual 17


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Valid date range from January 1, 4712 BC, to December 31, 9999 AD. The default
format is determined explicitly by the NLS_ DATE_FORMAT parameter or
DATE implicitly by the NLS_TERRITORY parameter. The size is fixed at 7 bytes. This data
type contains the datetime fields YEAR, MONTH, DAY, 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
TIMESTAMP fractional_seconds_precision are 0 to 9. The default is 6. The default
[(fractional_seconds_ format is determined explicitly by the NLS_TIMESTAMP_FORMAT parameter or
precision)] implicitly by the 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.

231-CIS-3 | Lab Manual 18


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

DDL commands:
• To delete or drop a table ( if exists )
drop table student;
• 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));
• Add a new column to the table
alter table student add avg number(5,2);
• To increase the size of the column
alter table student modify avg number(6,2);
• To see the structure of the table
desc student

231-CIS-3 | Lab Manual 19


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

DML and TCL commands:


• Insert data into the table:
insert into student values(432820234,’Saeed’,’CE’,100,100,100,0);
insert at least three students.
• To update the total column.
update student set total=m1+m2+m3;
• View the data contents of the table.
select * from student;
• To save the data of the table permanently:
commit;
• Insert once again some student:
insert into student values(432820237,’Majid’,’CE’,100,95,98,0);
• Practice rollback command:
rollback;
After the rollback the above student 432820237 will be deleted.
Execute the update command again and commit to save.

• To delete all the students.


delete from student;
• Undelete the data using rollback again.
rollback;
• To delete a single or particular record:
delete from student where univno=432820123;
• Update avg column of the table
update student set avg=total/3;
• To change the name of m3 to final
Alter table student rename column m3 to final;
• To delete a column from the table
alter table student drop column avg;

231-CIS-3 | Lab Manual 20


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Database Constraints
• primary key:
o 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.
• not null:
o This constraint is applied on those columns which cannot be left empty like name, course etc.
• unique:
o is applied to those columns whose value will be unique like for example: idno, mobileno,
account_no etc.
• check:
o 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.The example below shows how to apply the above
constraints on the student table.

To create the following table with the above constraints.


univno Name Idno course m1 m2 m3 total

1. Drop the previous table student that you created in the last class
drop table student;
2. 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));
3. To see the structure of the table
desc student

231-CIS-3 | Lab Manual 21


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

4. Insert data into the table:


insert into student
values(432820234,’Saeed’,1084567867,’CE’,100,100,100,0);
insert at least three students

5. 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:
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;

231-CIS-3 | Lab Manual 22


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Foreign key constraint


Foreign Key: A key applied on detail (child) table whose primary key is in the master (parent) table.

dep
dno Dname loc

employee
empno ename mgr job sal comm dno

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. To see the structure of the table
desc dep
desc employee
4. 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’);

231-CIS-3 | Lab Manual 23


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

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

insert into employee values


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

6. Check the data in dep table:


select * from dep;
7. Check the data in employee table:
select * from employee;
8. To save the data of the table permanently:
commit;
9. To add primary key constraints
ALTER TABLE employee ADD constraint PK_dno PRIMARY KEY (dno);
10. To drop primary key constraints
ALTER TABLE employee drop constraint PK_dno;
11. To add foreign key constraints
ALTER TABLE employee ADD CONSTRAINT fk_dno FOREIGN KEY (dno) REFERENCES
dept(dno);
12. 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 no matter the order of
the table creation is.
Drop table table_name cascade constraints;

231-CIS-3 | Lab Manual 24


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

SQL: Querying databases (SELECT, WHERE, LIKE, IN, AND/OR/NOT, ORDER


LAB-4
BY)

This lab teaches the following topics:


• Implementation of various types of operators using select command.
• using 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
Tests for nulls. This is the only operator that should be used
IS [NOT] NULL
to 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.

231-CIS-3 | Lab Manual 25


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Use the following table (emp) to complete examples:

empno ename Job Sal City


1 Ahmad manager 2000 Abha
2 Nasser secretary 4000 Jeddah
3 Ali salesman 20000 Abha
4 Fahad salesman null Najran
1. Use of Arithmetic Operators in select:
select empno,ename,sal from emp;
select empno,ename,sal, sal+500 from emp;
select empno,ename,sal, sal*2 from emp;
select empno,ename,sal, sal+(sal+40*sal/100) from emp;
2. Use of Comparison Operators in select and use of where clause:
select * from emp where sal<1000;
select * from emp where sal>1000;
select * from emp where sal<=3000;
select * from emp where sal>=3000;
select * from emp where sal!=5000;
select * from emp where sal=3000;
3. Use of logical operators:
select * from emp where job=’MANAGER’ and sal>=3000;
select * from emp where job=’MANAGER’ or sal>=3000;
select * from emp where job=’SALESMAN’ and not sal>=3000;
4. Use of Other operators using select:
select * from emp where sal between 1000 and 3000;
select * from emp where ename like ‘N%’;
select * from emp where ename like ‘_hmad’;
select * from emp where sal in (2000,1250,4000);
select * from emp where sal is null;

231-CIS-3 | Lab Manual 26


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Order by clause
● Order by column-list
● Sorts the result according to specified criteria
● Default is ascending order
● Add desc if descending order
Example:

1. Return employees by ascending order of their names


Select * from emp order by ename;
2. Return employees by decending order of their names
Select * from emp order by ename desc;

231-CIS-3 | Lab Manual 27


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

LAB-5 SQL Querying Database (Aggregation, Group By, Having)

Objectives:
This session aims to teach students the following:
1. To identify the available group functions.
2. To describe the use of group functions.
3. To group data using group by clause.
4. To use comparison over aggregation.
5. To include or exclude grouped rows by using having clause.
6. To sort query results using order by clause.

Prerequisites
• Review the given theoretical lectures.
• Use SQL Developer to implement the given SQL commands.
• Use to' hr' scheme to work on the available tables.
• Explore employees table.
Learning resources
• All activates are collected from Chapter 2, the textbox: Database System Concepts, Seventh Edition, Avi
Silberschatz, Henry F. Korth, S. Sudarshan, McGraw-Hill, ISBN 9780078022159 (February, 2019)
• Any useful online resources.
Session Activates
• Based on employees table, read each activity from A to F carefully and write the appropriate SQL
commands.
Practice Aggregate Functions
Before starting, remember that :
• Aggregate Functions operate on sets of rows to give one result per group. There are many aggregate
functions, however, only we will cover the following: SUM(), AVG(), COUNT(), MAX() and MIN() during
this session.
• SUM() and AVG() functions are used for numeric data. While MAX() and MIN() functions are used for
any type of data
• COUNT () has three formats:
o COUNT(*) ; returns the number of rows in a table
231-CIS-3 | Lab Manual 28
College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

o COUNT (expr) ; returns the number of rows with non-null values. Identified by expr.
o COUNT (DISTINCT EXPR) - ; returns the number distinct non null rows identified by expr.
Imagine that your manager requests you some information about his employees as follows:
1. How many employees are currently working at the company?
SELECT count(emp_id) // count(*)FROM employees;
2. How many job ids that have been occupied in the company? Please avoid repetition of jobs.
SELECT COUNT(distinct job_id)FROM employees;
[note: later, you will learn how to use join commands to make this query more meaningful]

3. Compute the total number of salary that earned by all employees.


SELECT SUM(salary) FROM employees;
4. What is the lowest, average and highest amount of salary that earned by employees?
SELECT MIN(salary),AVG(salary), MAX(salary)FROM employees;

Comparison over Aggregation


The given query below aims to return the id of the employee who earns the highest salary:
SELECT emp_id
FROM employees
WHERE salary = MAX (salary);
When you tried to execute it, an error-message was fired.
1. What is the problem with this query?
Answer: Aggregation cannot appear directly in WHERE clause. 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.

2. How can you modify the query to solve the problem?


Answer: Using subquery because it will be processed first in queries. The query can be modified as :
SELECT emp_id
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

GROUP BY clause
Before starting remember that:
• Using group by clause to divide rows in the table into smaller groups.
231-CIS-3 | Lab Manual 29
College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

• Using group by clause when all columns in the select clause are not in group functions must be in
group by clause.

1. Write a query that finds the job id, total , highest , lowest and average salaries that paid for employees
per job ids.
SELECT job_id,
SUM(salary),AVG(salary),MAX(salary),MIN(salary)
FROM employees
GROUP BY job_id;
Using group by clause for multiple columns:
2. Write a query that finds job id , department id , the number of emplyees, the total , highest , lowest
and average salaries that paid for employees per job ids and department id .
SELECT job_id, department_id ,
COUNT(emp_id), SUM(salary), AVG(salary), MAX(salary), MIN(salary)
FROM employees
GROUP BY job_id, department_id;
The group by clause column does not have to be in the select list.
3. Write a query that finds the total , highest , lowest and average salaries that paid for employees per
job ids.
SELECT SUM(salary),AVG(salary),MAX(salary),MIN(salary)
FROM employees
GROUP BY job_id;

HVING CLAUSE
Before starting remember that:
• Use the having clause to restrict groups when:
o Rows are grouped
o Group function is applied
o Groups matching the having clause are displayed

1. Write a query to display the highest salary for department id such that the highest salary must exceeds
10000. Sort results based on the sum of salary
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary) >10000

231-CIS-3 | Lab Manual 30


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

ORDER BY SUM(salary);

231-CIS-3 | Lab Manual 31


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Self-Practice Exercises
Practice the following exercises alone and then try compare your answers with your classmates.

• Activity 1: Write a query that returns employees' first names and last names provided that first name
must be in ascending order and last name must be in descending order.

• Activity 2:Write a query to find out the ids, first names, job ids and hire dates for the first and last hired
employees in the company?

• Activity 3: Using country table to write a query that lists the number of countries in each region.

• Activity 4: Using country table to write a query that lists the number of countries in each region,
sorted from high number to low (only include regions with more than 5 countries).

231-CIS-3 | Lab Manual 32


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

LAB-6 SQL Querying Database (Joins, Views)

Objectives
This session aims to teach students how to get acquainted with different types of joins including:
1. To write SQL statements to access data from more than one table (two or Multi-Table Join)
2. To view data that generally does not meet a join condition by using outer join (natural join, left outer
join, right outer join and full outer join.)
3. To write SQL statements to create, update or drop views.
Prerequisites
● Review the given theoretical lectures.
● Use SQL Developer to implement the given SQL commands.
● Create customers and orders tables to apply your codes on.
Learning resources
● All activates are collected from Chapter 2, the textbox: Database System Concepts, Seventh Edition, Avi
Silberschatz, Henry F. Korth, S. Sudarshan, McGraw-Hill, ISBN 9780078022159 (February, 2019)
● Any useful online resources.
Before to Start Remember

JOIN
● 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:

i. A join condition is omitted


ii. A join condition is invalid
Note: To avoid Cartesian products always include a valid join condition in a where clause.
To do so, you need to apply the following steps:
1) 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.
2) Put those tables in the from clause.
3) 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.
231-CIS-3 | Lab Manual 33
College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Session Activities
We will use the following two tables to apply different types of join queries. So please create 2 tables
according to the given data below:

1) 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
2) Orders table
oid o_date 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

INNER JOIN
● 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.

1) What are the outputs of the following SQL statements? Do you get different results?
A B
SELECT * SELECT *
FROM Customers FROM Customers, Orders
INNER JOIN Orders WHERE Customers.id = Orders.id;
ON Customers.id = Orders.id;

Natural JOIN
Natural join: matches tuples with the same values for all common attributes, and retains only one copy of
each common column.
Natural Join: Guidelines
- The associated tables have one or more pairs of identically named columns.
- The columns must be the same data type.
- Don’t use ON clause in a natural join.

231-CIS-3 | Lab Manual 34


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Use NATURAL JOIN to retrieve all information from customers and orders.
Answer:
SELECT *
FROM Customers
NATURAL JOIN Orders;

Note that: Natural join omits one of the identical columns (id)

What are the outputs of the following SQL statements? Do you get different results?
A B
SELECT * SELECT *
FROM Customers FROM Customers
INNER JOIN Orders NATURAL JOIN Orders;
ON Customers.id = Orders.id;

OUTER JOIN
● 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.

LEFT OUTER JOIN


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

Write a query to retrieve some information of customers, such as id and names. Additionally, in the same
query find out the corresponding orders in terms of id, amount of orders and date of orders. Please notice
that your main concern is to retrieve all customers whether they have corresponding orders or not.
Answer:
SELECT Customers.id, name, oid, amount, o_date
FROM Customers
LEFT JOIN Orders
ON Customers.id = Orders.id;
231-CIS-3 | Lab Manual 35
College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

1) What would be the outputs when you exchange the places of tables where Orders is placed in FORM
clause and Customers will be put in LEFT JOIN clause.
Answer:
SELECT Customers.id, name, oid, amount, o_date
FROM ORDERS
LEFT JOIN Customers
ON Customers.id = Orders.id;

RIGHT OUTER JOIN


● 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.
For all rows in B that have no matching rows in A, Oracle returns null for any select list expressions
containing columns of A.

1) Write a query to retrieve some information of customers, such as id and names. Additionally, in the same
query find out the corresponding orders in terms of id, amount of orders and date of orders. Please notice
that your main concern is to retrieve all Orders regardless of their customers.
Answer:
SELECT Customers.id, name, oid, amount, o_date
FROM Customers
RIGHT JOIN Orders
ON Customers.id = Orders.id;

231-CIS-3 | Lab Manual 36


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

FULL OUTER JOIN

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

1) Execute the following query. What do you notice about the results?
Answer:
SELECT Customers.id, name, oid, amount, o_date
FROM Customers
FULL JOIN Orders
ON Customers.id = Orders.id;

Self-JOIN
● 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.
Based on the Customers table, return a list of employees and their supervisors in terms of ids and names,
and give meaningful aliases for each returned column to clarify the results.
Answer:
SELECT c1.id AS Customer_Id, c1.name AS Customer_Name,
c2.id AS Supervisor_id, c2.name AS Supervisor_name
FROM Customers c1, Customers c2
WHERE c1.supervisor_id = c2.id;

Return the id, name and salary of customers who have salaries greater than 'Fahad'.
Answer:
SELECT c2.id, c2.name, c2.salary
FROM Customers c1, Customers c2
WHERE c1.name='Fahad' AND c2.salary > c1.salary;

231-CIS-3 | Lab Manual 37


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

VIEWS
In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual
relations stored in the database.). A view can contain all rows of a table or selected rows from a table. A
view can be created from one or many tables which depends on the written SQL query to create a view.

Creating views
The basic CREATE VIEW syntax:
create view v as < query expression >

Where <query expression> is any legal SQL expression and the view name is represented by v.
Create a view from CUSTOMERS table to have customer name and age.
create view customer_view as
select name, age
from customers;

To show the view, use:


select * from customer_view;

Inserting rows into a view


Add a new tuple to customer_view which we defined earlier
insert into customer_view values('Omar',40);

Here we cannot insert rows in CUSTOMERS_VIEW because we have not included all the NOT NULL columns
in this view, otherwise you can insert rows in a view in similar way as you insert them in a table.

Updating views
Most SQL implementations allow updates only on simple views
§ The from clause has only one database relation.
§ The select clause contains only attribute names of the relation, and does not have any expressions,
aggregates, or distinct specification.
§ Any attribute not listed in the select clause can be set to null
§ The query does not have a group by or having clause.
Update the age of Salem
update customer_view set age = 35 where name='Salem';

231-CIS-3 | Lab Manual 38


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Deleting rows from a view


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT commands
apply to the DELETE command.

Delete a record having AGE= 22.


delete from customer_view where age=22;

Dropping a view
Delete customer_view if you no longer need it.
drop view customer_view;

231-CIS-3 | Lab Manual 39


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Self-Practice Exercises
Practice the following exercises alone and then try to compare your answers with your classmates. [if you
use Live Oracle SQL website, use hr.jobs and hr.employees to access these tables. ]
Activity 1:
Assume that the source and target are JOBS and EMPLOYEES tables from the HR schema, respectively. The
EMPLOYEES table contains the following columns named EMPLOYEES_ID,SALARY and COMMISSION_PCT. The
JOBS table consists of the following columns named JOB_ID and JOB_TITLE. The data in these two tables is
related to each other based on the common JOB_ID column.
Do the following queries:
1. Insert the following values into the Jobs table.
Job_id Job_title Min_salary Max_salary
TR Trainer 5000 6000
HR Human Resources 5400 8000

● Query 1: Display job_id , job_title for all jobs including in jobs table.
● Query 2: Display employee_id, salary and commission_pct for all employees including in employees table.
● Query 3: Display job_id , job_title , employee_id, salary and commission_pct from both jobs and
employees tables for only employees whose salary is greater than 15000 using inner join.
● Query 4: Display job_id , job_title , employee_id, salary and commission_pct from both jobs and
employees tables for only employees whose salary is greater than 5000 using left outer join.
● Query 5: Display job_id , job_title , employee_id, salary and commission_pct from both jobs and
employees tables for only employees whose salary is greater than 5000 using right outer join.
● Query 6: Display job_id , job_title , employee_id, salary and commission_pct from both jobs and
employees tables for only employees whose salary is greater than 5000 using full outer join.
Query 7: Display job_id , job_title , employee_id, salary and commission_pct from both jobs and employees

231-CIS-3 | Lab Manual 40


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

LAB-7 Functions, Stored Procedures, Triggers

Objectives
This session aims to teach the following:
1. What is PL/SQL?
2. The block structure of PL/SQL
3. Anonymous vs. Named PL/SQL blocks
4. Procedures and user-defined functions
5. triggers
Prerequisites
● Review the given theoretical lectures.
● Use SQL Developer to implement the given SQL commands.
● Create customers and orders tables to apply your codes on.
Learning resources
● All activates are collected from Chapter 2, the textbox: Database System Concepts, Seventh Edition, Avi
Silberschatz, Henry F. Korth, S. Sudarshan, McGraw-Hill, ISBN 9780078022159 (February, 2019)
● Any useful online resources.
Session Activities
We will use the emp table to apply procedures, functions and triggers. So please create the emp table according to the
given data below:
Emb
eid name Dept_name salalry
1 Ali IT 7000
2 Ahmad IS 9000
3 Fahad CS 15000

PL/SQL and its block structure


PL/SQL stands for Procedural Language Extension to SQL. PL/SQL extends SQL by adding programming structures and
subroutines available in any high-level language. It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL.
A block is the most basic unit in PL/SQL. All PL/SQL programs are combined into blocks. PL/SQL blocks can be divided
into two groups: named and anonymous.
Anonymous PL/SQL blocks:
• block has no name
• Code is NOT stored in database (discarded after execution)
• Cannot accept or pass parameter values
Named PL/SQL blocks:
• Stored as compiled objects in database (functions, procedures)
• Can take parameters as input
• Can be called by other programs

231-CIS-3 | Lab Manual 41


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

PL/SQL block has the following structure: (The declaration and exception-handling sections are optional)

declare
declaration of variables;
begin
statements;
exception
handle exceptions;
end;

Displaying PL/SQL Output

Use DBMS_OUTPUT package to output:


• DBMS_OUTPUT.PUT();
output the item without end-of-line
• DBMS_OUTPUT.PUT_LINE();
output an end-of-line
To enable output from PL/SQL programs, use the following command: (You need to turn on serveroutput every time you
log in)
SET SERVEROUTPUT ON;
Example:
SET SERVEROUTPUT ON;
declare
greeting varchar2(50) := 'Hello World';
x integer := 10;
begin
dbms_output.put(greeting);
dbms_output.put_line(' Hello World');
dbms_output.put_line(x);
dbms_output.put_line(10);
end;

Output:

231-CIS-3 | Lab Manual 42


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Procedures
A procedure is a named (stored) module that performs one or more actions; it does not need to return any values. The
syntax for creating a procedure is as follows:

CREATE OR REPLACE PROCEDURE procedure_name
(parameter datatype)
IS | AS Header
local variable declarations

BEGIN
program statements Body
END;

Example: Create a procedure to find the sum and product of two numbers
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;

Calling a procedure
In general, procedures can be called using:
1. An anonymous PL/SQL program:
Begin
disp_AB(10,20);
end;
2. one of the following commands:
call disp_AB(10,20);
exec disp_AB(10,20);

Example: Using Emp table, create a procedure get_salary with an input parameter emp_id, and print the salary
of the employee with that id. Then execute this procedure with e_id = 1.

CREATE OR REPLACE PROCEDURE Get_salary (emp_id INT) IS
Emp_salary int;

BEGIN
select salary into Emp_salary from emp where eid = emp_id;
DBMS_OUTPUT.PUT_LINE('salary of ' ||emp_id || ' is ' || emp_salary);
END;

call Get_salary(1);

231-CIS-3 | Lab Manual 43


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Functions
A function that is stored in the database is much like a procedure in that it is a named PL/SQL block that can take
parameters and be invoked. Function differs from a procedure in that it (function) returns a single value. The syntax for
creating a function is as follows:

CREATE [OR REPLACE] FUNCTION function_name


(parameter list) Header
RETURN datatype
IS

BEGIN
<body> Body
RETURN return_value;
END;


** There is a return data-type in header and a return statement in body. The return command in header specifies
data type of value the function will return (no need to specify a variable name). The return command in body
specifies actual value returned by the function.

Example: Create a function to find the sum of two numbers
create or replace function Sum_AB (A number, B number)
return number
is
result number;
begin
result := A + B;
return result;
end;


Calling a Function:
In general, functions can be called using:
1. An anonymous PL/SQL program. There must be a variable to store returned value.
declare
result number;
begin
result := sum_AB(10,20);
dbms_output.put_line(result);
end;

2. the command "selectFunction_Name(paramertes) from dual;"
select sum_AB(10,20) from dual;

Example: Using Emp table, create a function return_salary with an input parameter emp_id, and print the
salary of the employee with that id. Then execute this function with e_id = 1.

231-CIS-3 | Lab Manual 44


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

create or replace function return_salary (emp_id in number)


return number
is
e_sal number;
begin
select salary into e_sal from emp where eid = emp_id;
return e_sal;
end;

Calling the function (return_salary)


declare
e_sal number;
begin
e_sal := return_salary(1);
dbms_output.put_line(e_sal);
end;

select return_salary(1) from dual;

Triggers
A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database.
Triggers are used to
• Enforce complex constraints (such as referential integrity not supported by declarative integrity constraints) or
business rules (such as an account cannot have a negative balance)
• Audit the changes to the tables
There are two types of triggers:
• Statement Level: trigger fires once, regardless of how many rows are modified
• Row Level: trigger fires once for each row that is affected
To design a trigger mechanism, we must:
• Specify the conditions under which the trigger is to be executed (fired).
• Specify the actions to be taken when the trigger executes.
Creating a Statement-Level Trigger
The syntax for creating statement-level trigger is as follows:
CREATE OR REPLACE TRIGGER trigger_name
{BEFORE|AFTER} {INSERT or UPDATE or DELETE} ON
table_name
[DECLARE
declare local variables here]
BEGIN
trigger body
END;

ü Insert, delete, and update are trigger events (types of modifications that will fire the trigger). Use OR if you
want to fire the trigger in multiple types
ü Before means “before trigger,” and after means “after trigger”.
Example: Create a trigger on Emp table, and fires it when someone update, insert, or delete the Emp table. The
trigger will print out the user who does the modification and the time. The ‘user’ system variable holds the current
user. Then test your trigger by updating the Emp table.

231-CIS-3 | Lab Manual 45


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

create or replace trigger audit_emp


after insert or update or delete on emp
begin
dbms_output.put_line(user||' modifies the table Emp on '||sysdate);
end;

--Test the trigger


update emp set salary = salary + 500;

Creating a Row-Level Trigger


The syntax for creating a row-level trigger is as follows:
CREATE OR REPLACE TRIGGER trigger_name
{BEFORE|AFTER} {INSERT or UPDATE or DELETE} ON table_name
FOR EACH ROW [WHEN (condition)]
[DECLARE …]
BEGIN
trigger body
END;

Example: Create a row-level trigger on Emp such that if its department name (dept_name) gets changed, print
out: name + ‘has changed dept from’ + dept_name + ‘to’ dept_name. Then test your trigger by updating the Emp
table.

create or replace trigger change_dept


after update on emp
for each row when (new.dept_name <> old.dept_name)
begin
dbms_output.put_line(:new.name||' has changed dept from '
||:old.dept_name || ' to '||:new.dept_name) ;
end;

--Test the trigger


update emp set dept_name='IS' where eid=1;

ü The new variable represents the row after modification


ü The old variable represents the row before modification
ü Use as ‘new’ in when condition
ü Use as ‘:new’ in trigger body
Output

231-CIS-3 | Lab Manual 46


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

LAB-8 Entity-Relationship Diagram ERD

Objectives
This session will introduce basic concepts about
• Entity-Relationship Model
• Entities, attributes, and relationships.
• Create ERD based on specific scenarios.
Prerequisites
● Review the given theoretical lectures.
● Use Creately to draw ERDs
Before to Start Remember
The ER or (Entity Relational Model) is a high-level conceptual data model diagram. Entity-Relation model is
based on the notion of real-world entities and the relationship between them.
ER modeling helps you to analyze data requirements systematically to produce a well-designed database. So,
it is considered a best practice to complete ER modeling before implementing your database.
What is ER Diagram?
Entity relationship diagram displays the relationships of entity set stored in a database. In other words, we can
say that ER diagrams help you to explain the logical structure of databases. At first look, an ER diagram looks
very similar to the flowchart. However, ER Diagram includes many specialized symbols, and its meanings make
this model unique.
Components of the ER Diagram
This model is based on three basic concepts:
• Entities
• Attributes

• Relationships

Example
For example, in a University database, we might have entities for Students, Courses, and Lecturers. Students
entity can have attributes like Rollno, Name, and DeptID. They might have relationships with Courses and
Lecturers.

231-CIS-3 | Lab Manual 47


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

WHAT IS ENTITY?
An entity can be place, person, object, event or a concept, which stores data in the database. The
characteristics of entities are must have an attribute, and a unique key. Every entity is made up of some
'attributes' which represent that entity.
• Person: Employee, Student, Patient
• Place: Store, Building
• Object: Machine, product, and Car
• Event: Sale, Registration, Renewal
• Concept: Account, Course

Example of Entities:
A university may have some departments. All these departments employ various lecturers and offer several
programs.
Some courses make up each program. Students register in a particular program and enroll in various courses.
A lecturer from the specific department takes each course, and each lecturer teaches a various group of
students.

Left to Right > Student attend course


Right to Left > Course attended by student

231-CIS-3 | Lab Manual 48


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Relationship
Relationship is nothing but an association among two or more entities. E.g., a student can attend many classes

Left to Right > many Students attend many courses


Right to Left > many Courses attended by many students
Relationships and Cardinality
Defines the numerical attributes of the relationship between two entities or entity sets. Different types of
cardinal relationships are:

• one-to-one (1:1)
• one-to-many (1:N)
• many-to-many (N:M)

Left to Right > one or more Students may attend many classes
Right to Left > many Course attended by at least one or more students
Attributes
• It is a single-valued property of either an entity-type or a relationship-type.
• For example, a lecture might have attributes: time, date, duration, place, etc.

• An attribute is represented by an Ellipse

231-CIS-3 | Lab Manual 49


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Steps to Create an ERD


Following are the steps to create an ERD.

Attribute Relationship Cardinality


Enitiy Identification Create ERD
Identification Identification Identification

EXAMPLE:
In a university, a Student enrolls in Courses. A student must be assigned to at least one or more
Courses. Each course is taught by a single Professor. To maintain instruction quality, a Professor can
deliver only one course.

Step 1) Entity Identification


• Student
• Course
• Professor

Step 2) Attribute Identification


• Student: id, name
• Professor: id, name
• Course: id, name

Step 3) Relationship Identification


• The student is assigned a course
• Professor delivers a course

Step 4) Cardinality Identification


• A student can be assigned multiple courses
• A Professor can deliver only one course

Step 5) Create the ERD (USING CREATELY) www.creately.com

231-CIS-3 | Lab Manual 50


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Case Study -1
UPS prides itself on having up-to-date information on the processing and current location of each shipped
item. To do this, UPS relies on a company-wide information system.
Shipped items are the heart of the UPS product tracking information system. Shipped items can be
characterized by item number, weight, destination, and final delivery date. One or more shipped items are
received into the UPS system at only one retail center.
Retail centers are characterized by their type, ID, and address. Many shipped items are shipped to their
destination via one or more standard UPS transportation events (i.e., flights, truck deliveries). These
transportation events are characterized by a unique scheduleNumber, a type (e.g, flight, truck), and a
deliveryRoute.
Step 1) Entity Identification
• Shipped Items
• Retail Center
• Transportation Event

Step 2) Attribute Identification


• Shipped Items : item number, weight, destination, final delivery date
• Retail Center: type, ID, address
• Transportation Event: scheduleNumber, type, deliveryRoute.

Step 3) Relationship Identification


• One or more shipped items are received into the UPS system at only one retail center.
• Many Shipped items are shipped via one or more standard UPS transportation events

Step 4) Cardinality Identification


• One or more shipped items are received into the UPS system at only one retail center.
• Many Shipped items are shipped via one or more standard UPS transportation events.

231-CIS-3 | Lab Manual 51


College of Computer Science ‫ﻛﻠﻴﺔ ﻋﻠﻮﻡ ﺍﻟﺤﺎﺳﺐ ﺍﻵﻟﻲ‬
Department of Information Systems ‫ﻗﺴﻢ ﻧﻈﻢ ﺍﻟﻤﻌﻠﻮﻣﺎﺕ‬

Step 5) Create ERD

231-CIS-3 | Lab Manual 52

You might also like