231 - CIS - Lab Manual
231 - CIS - Lab Manual
231 - CIS - Lab Manual
231-CIS-3
Database Management System
Department of Information systems
College of Computer Science
King Khalid University
(Lab Manual)
Semester I (2021)
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
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:
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 Query Language (DQL):
Command Description
SELECT Retrieves certain records from one or more tables
● 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
● Click Extract
● 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”
Now, you have successfully downloaded and installed Oracle XE on your system.
● 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”
● Go inside the folder and right-click on the application named “sqldeveloper” and choose “create
shortcut”
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
3. Now retrieve all instructors whose salary greater than $50,000 and work at Physics department
Answer: δ salary >50000 ˄dept name =“Physics” (instructor)
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.
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.
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'.
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'.
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
5) Finally, find all the courses taught in the Fall 2017 semester but not in Spring 2018 semester.
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.
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
SQL: Oracle data types, Creating, Updating and Deleting Schema and Records
LAB-3
(CREATE, INSERT, UPDATE, ALTER, DELTE, DROP), Integrity Constraints
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.
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.
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
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.
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
dep
dno Dname loc
employee
empno ename mgr job sal comm dno
5. Insert data into the detail table later. Example is given below:
insert into employee values
(1111,10,’Saad’,‘President’,null,20000,null);
** 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;
Logical Operators
and
or
not
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.
Order by clause
● Order by column-list
● Sorts the result according to specified criteria
● Default is ascending order
● Add desc if descending order
Example:
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]
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
ORDER BY SUM(salary);
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).
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:
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.
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.
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;
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;
● 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;
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;
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';
Dropping a view
Delete customer_view if you no longer need it.
drop view customer_view;
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
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 block has the following structure: (The declaration and exception-handling sections are optional)
declare
declaration of variables;
begin
statements;
exception
handle exceptions;
end;
Output:
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);
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:
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.
declare
e_sal number;
begin
e_sal := return_salary(1);
dbms_output.put_line(e_sal);
end;
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.
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.
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.
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.
Relationship
Relationship is nothing but an association among two or more entities. E.g., a student can attend many classes
• 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.
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.
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